Пример #1
0
 def addText(self, data_box):
     text = data_box.getText()
     frame_style = Style(name='FrameStyle', family='graphic')
     debug('Angle: %s', data_box.text_data.angle)
     angle = data_box.text_data.angle
     if angle:
         frame_style = Style(name='FrameStyleRotated', family='graphic')
     x, y, width, height = data_box.getBoundsPrintSize(
         self.current_page_resolution)
     frame = Frame(stylename=frame_style,
                   width=str(width) + 'in',
                   height=str(height) + 'in',
                   x=str(x) + 'in',
                   y=str(y) + 'in',
                   anchortype='paragraph')
     if angle:
         frame.addAttribute(
             'transform', 'rotate (%s) translate (%scm %scm)' %
             (abs(math.radians(angle)), x, y))
     self.current_page.addElement(frame)
     textbox = TextBox()
     frame.addElement(textbox)
     for line in text.split('\n'):
         textbox.addElement(
             P(stylename=self.__handleFrameStyle(data_box.text_data),
               text=line))
def beehive(an_odt, a_graphic_style, an_h, a_w, an_x, a_y, a_z):
	# http://en.wikipedia.org/wiki/Frame_(beehive)
	an_odt.styles.addElement(a_graphic_style)
	a_frame = Frame(stylename=a_graphic_style, height=an_h, width=a_w,
					x=an_x, y=a_y, zindex=a_z)
	a_textbox = TextBox()
	a_frame.addElement(a_textbox)
	return {"frame" : a_frame, "textbox" : a_textbox}
Пример #3
0
 def add_image(self, path):
     page = Page(masterpagename=self.masterpage)
     photoframe = Frame(
         stylename=self.photostyle, width='%fpt' % self.width,
         height='%fpt' % self.height, x='0pt', y='0pt')
     self.doc.presentation.addElement(page)
     page.addElement(photoframe)
     href = self.doc.addPicture(path)
     photoframe.addElement(Image(href=href))
Пример #4
0
 def addImage(self,image_path,name):
     if not name:
         name = image_path
     p = P()
     self.textdoc.text.addElement(p)
     href = self.textdoc.addPicture(image_path)
     f = Frame(name=name, anchortype="paragraph", width="17cm", height="7.5cm", zindex="0")
     p.addElement(f)
     img = Image(href=href, type="simple", show="embed", actuate="onLoad")
     f.addElement(img)
Пример #5
0
 def picprint(num):
     picref = textdoc.addPictureFromFile(data[num].picpath)
     fftpicref = textdoc.addPictureFromFile(data[num].fftpicpath)
     pf = Frame(width="8cm", height="6cm", x="0cm", y="0cm")
     pf2 = Frame(width="8cm", height="6cm", x="10cm", y="0cm")
     p = P(stylename=picturetext)
     pf.addElement(Image(href = picref))
     pf2.addElement(Image(href = fftpicref))
     p.addElement(pf)
     p.addElement(pf2)
     ent(p,1)
     p.addText(u"Рис." + str(picnum) + u' ' + data[num].params['measure'] + u" от времени и его амплитудно-частотная характеристика" )
     ent(p,1)
     return p
Пример #6
0
 def addImage(self, data_box):
     format = 'PNG'
     image_file = tempfile.mkstemp(suffix='.' + format)[1]
     data_box.image.save(image_file, format=format)
     x, y, width, height = data_box.getBoundsPrintSize(
         self.current_page_resolution)
     photo_frame = Frame(stylename=self.photo_style,
                         x='%sin' % x,
                         y='%sin' % y,
                         width='%sin' % width,
                         height='%sin' % height,
                         anchortype='paragraph')
     self.current_page.addElement(photo_frame)
     location = self.document.addPicture(image_file)
     photo_frame.addElement(Image(href=location))
     self.temp_images.append(image_file)
Пример #7
0
 def addImage(self, data_box):
     format = "PNG"
     image_file = tempfile.mkstemp(suffix="." + format)[1]
     data_box.image.save(image_file, format=format)
     x, y, width, height = data_box.getBoundsPrintSize(self.current_page_resolution)
     photo_frame = Frame(
         stylename=self.photo_style,
         x="%sin" % x,
         y="%sin" % y,
         width="%sin" % width,
         height="%sin" % height,
         anchortype="paragraph",
     )
     self.current_page.addElement(photo_frame)
     location = self.document.addPicture(image_file)
     photo_frame.addElement(Image(href=location))
     self.temp_images.append(image_file)
Пример #8
0
def Page_Rect_get_Text_odf(doc, name, page_num, rects, hierarchy, output,
                           style_p):
    page = doc[page_num]
    words = page.getText("words")
    output.text.addElement(P(stylename=style_p, text="_" * 30))
    output.text.addElement(P(stylename=style_p, text=f"page {page_num+1}"))
    for i in range(rects.shape[0]):
        if hierarchy[i, 3] == -1:
            output.text.addElement(P(stylename=style_p, text=""))
            rect = Rect(rects[i, 0], rects[i, 1], rects[i, 2], rects[i, 3])
            mywords = [w for w in words if Rect(w[:4]) in rect]
            mywords.sort(key=itemgetter(3,
                                        0))  # sort by y1, x0 of the word rect
            group = groupby(mywords, key=itemgetter(3))
            out_text = P(stylename=style_p, text="")
            for y1, gwords in group:
                out_text.addText(" ".join(w[4]
                                          for w in gwords).replace("\n", " "))
                out_text.addText(" ")
            output.text.addElement(out_text)
        if hierarchy[i, 3] != -1:
            output.text.addElement(P(stylename=style_p, text=""))
            out_img = P()
            #ncc=int(hierarchy[i,3])
            ncc = i
            clip = Rect(rects[ncc, 0], rects[ncc, 1], rects[ncc, 2], rects[ncc,
                                                                           3])
            pix = page.getPixmap(matrix=Matrix(2, 2), clip=clip)
            name_image = f"Pictures/image-{page.number}-{i}.png"
            #liste_tampon.append(name_tampon)
            #pix.writePNG(name_image)
            pix_png = pix.getPNGData()
            h = pix.height / pix.xres
            w = pix.width / pix.yres
            frame = Frame(width=f"{w}in",
                          height=f"{h}in",
                          anchortype="paragraph")
            href = output.addPicture(name_image,
                                     mediatype="png",
                                     content=pix_png)  #
            frame.addElement(Image(href=f"./{href}"))
            out_img.addElement(frame)
            output.text.addElement(out_img)
    return output
Пример #9
0
def write_image(image):
    """Write to output file image elements.

    Since, element with title 'Image' has special structure of 'c'(Content) field, that looks like:
    [[0], [1], [2]]
    where:
        [0] - list of attributes: identifier, classes, key-value pairs:
            ['id', [], [ ... , ['weight', '...in'], ['height', '...in'], ... ] - we get sizes there.
        [1] - caption.
        [2] - ['src', 'title'] - source and title of image.
    we should parse it especially.

    Args:
        image - element with title 'Image'.

    """
    global image_counter
    global saved_hr
    if image_counter == -1:
        return
    if image_counter == 0:
        saved_hr = load_images(args.input, ods)
        if len(saved_hr) == 0:
            image_counter = -1
            return
    if string_to_write:
        write_text()
    row = TableRow()
    cell = TableCell()
    w, h = count_size(image['c'][0][2], row)
    frame = Frame(width=w, height=h)
    img = Image(href=saved_hr[image_counter])

    table.addElement(row)
    row.addElement(cell)
    cell.addElement(frame)
    frame.addElement(img)

    image_counter = image_counter + 1
Пример #10
0
 def addImageHeaderFooter(self,header=None,footer=None):
     if header or footer:
         mp = MasterPage(name="Standard", pagelayoutname=self.pliheaderstyle)
         self.textdoc.masterstyles.addElement(mp)
         if header:
             h = Header()
             p = P()
             href = self.textdoc.addPicture(header)
             f = Frame(name="membrete", anchortype="paragraph", width="17cm", height="1.5cm", zindex="0")
             p.addElement(f)
             img = Image(href=href, type="simple", show="embed", actuate="onLoad")
             f.addElement(img)
             h.addElement(p)
             
             mp.addElement(h)
         if footer:
             fo = Footer()
             pn = PageNumber()
             fp = P(text=footer,stylename=self.footercenterstyle)#FIXME: Pagen number shoulb be better
             fp.addElement(pn)
             fo.addElement(fp)
             mp.addElement(fo)
Пример #11
0
 def addText(self, data_box):
     text = data_box.getText()
     frame_style = Style(name="FrameStyle", family="graphic")
     debug("Angle: ", data_box.text_data.angle)
     angle = data_box.text_data.angle
     if angle:
         frame_style = Style(name="FrameStyleRotated", family="graphic")
     x, y, width, height = data_box.getBoundsPrintSize(self.current_page_resolution)
     frame = Frame(
         stylename=frame_style,
         width=str(width) + "in",
         height=str(height) + "in",
         x=str(x) + "in",
         y=str(y) + "in",
         anchortype="paragraph",
     )
     if angle:
         frame.addAttribute("transform", "rotate (%s) translate (%scm %scm)" % (abs(math.radians(angle)), x, y))
     self.current_page.addElement(frame)
     textbox = TextBox()
     frame.addElement(textbox)
     for line in text.split("\n"):
         textbox.addElement(P(stylename=self.__handleFrameStyle(data_box.text_data), text=line))
Пример #12
0
def export_presentation(photos, destination, openafter=False):
    if destination[-4:] != ".odp": destination += ".odp"
    
    doc = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="Layout")
    doc.automaticstyles.addElement(pagelayout)
    pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt", pageheight="600pt", printorientation="landscape"))

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    titlestyle = Style(name="Master-title", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="34pt"))
    titlestyle.addElement(GraphicProperties(fillcolor="#ffffff"))
    doc.styles.addElement(titlestyle)

    # Style for the photo frame
    photostyle = Style(name="Master-photo", family="presentation")
    doc.styles.addElement(photostyle)

    # Create automatic transition
    dpstyle = Style(name="dp1", family="drawing-page")
    # dpstyle.addElement(DrawingPageProperties(transitiontype="automatic", transitionstyle="move-from-top", duration="PT5S"))
    doc.automaticstyles.addElement(dpstyle)

    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="Master", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)
    
    for p in photos:
        path = p.getData()
        image = QImage(path)
        if(image.isNull()):
          continue

        w = image.width()
        h = image.height()

        if w > 720:
           h = float(h) * 720.0 / float(w)
           w = 720.0
        if h > 540.0:
           w = float(w) * 540.0 / float(h)
           h = 540.0

        page = Page(stylename=dpstyle, masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=titlestyle, width="720pt",
           height="56pt", x="40pt", y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text=p.name))

        offsetx = 400.0 - w/2.0
        photoframe = Frame(stylename=photostyle, width="%fpt" % w,
           height="%fpt" % h, x="%fpt" % offsetx, y="56pt")
        page.addElement(photoframe)
        href = doc.addPicture(path)
        photoframe.addElement(Image(href=href))
    
    os.remove(destination)
    doc.save(destination)


    if sys.platform.startswith('darwin'):
        subprocess.call(('open', destination))
    elif os.name == 'nt':
        os.startfile(destination)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', destination))
Пример #13
0
def coursePage(coursename, data, lang):
    coursetitle = H(stylename=h2style, text=coursename, outlinelevel=2)
    textdoc.text.addElement(coursetitle)
    blankline = P(text="")
    textdoc.text.addElement(blankline)

    for diagramtype in [pie, percent]:
        p = P()
        textdoc.text.addElement(p)
        img_path = path + coursename + "-All" + diagramtype
        href = textdoc.addPicture(img_path)
        f = Frame(name=coursename + diagramtype,
                  anchortype="paragraph",
                  width="17cm",
                  height="7.5cm",
                  zindex="0")
        p.addElement(f)
        img = Image(href=href, type="simple", show="embed", actuate="onLoad")
        f.addElement(img)

    if lang == "eu":
        subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
    else:
        subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
    textdoc.text.addElement(subjectsp)
    blankline = P(text="")
    textdoc.text.addElement(blankline)
    textList = List(stylename="L1")

    file = path + "ehunekoak-" + period + "-" + year + "-" + coursename + "None.csv"
    with open(file, 'r', encoding="UTF-8") as results:
        reader = csv.reader(results)
        headers = next(reader, None)  # get first row with headers
        for row in reader:
            if float(row[1]) < 70 and row[0] != "All":
                item = ListItem()
                if lang == "eu":
                    item.addElement(
                        P(text=row[0] + ": " + "{:.2f}".format(float(row[1])) +
                          "%"))
                else:
                    item.addElement(
                        P(text=ikasgai[row[0]] + ": " +
                          "{:.2f}".format(float(row[1])) + "%"))
                textList.addElement(item)
                textdoc.text.addElement(textList)

    for courselang in data.keys():
        coursetitle = H(stylename=h2style,
                        text=coursename + "-" + courselang,
                        outlinelevel=2)
        textdoc.text.addElement(coursetitle)
        blankline = P(text="")
        textdoc.text.addElement(blankline)

        for diagramtype in [pie, percent]:
            p = P()
            textdoc.text.addElement(p)
            img_path = path + coursename + "-" + courselang + diagramtype
            href = textdoc.addPicture(img_path)
            f = Frame(name=coursename + diagramtype + courselang,
                      anchortype="paragraph",
                      width="17cm",
                      height="7.5cm",
                      zindex="0")
            p.addElement(f)
            img = Image(href=href,
                        type="simple",
                        show="embed",
                        actuate="onLoad")
            f.addElement(img)

        blankline = P(text="")
        textdoc.text.addElement(blankline)

        if lang == "eu":
            subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
        else:
            subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
        textdoc.text.addElement(subjectsp)
        blankline = P(text="")
        textdoc.text.addElement(blankline)
        textList = List(stylename="L1")

        file = path + "ehunekoak-" + period + "-" + year + "-" + coursename + courselang + ".csv"
        with open(file, 'r', encoding="UTF-8") as results:
            reader = csv.reader(results)
            headers = next(reader, None)  # get first row with headers
            for row in reader:
                if float(row[1]) < 70 and row[0] != "All":
                    item = ListItem()
                    if lang == "eu":
                        item.addElement(
                            P(text=row[0] + ": " +
                              "{:.2f}".format(float(row[1])) + "%"))
                    else:
                        item.addElement(
                            P(text=ikasgai[row[0]] + ": " +
                              "{:.2f}".format(float(row[1])) + "%"))
                    textList.addElement(item)
                    textdoc.text.addElement(textList)

        for group in data[courselang]:
            if group in ["Bil", "Plur"]:
                #1 ESO-AG-AGBil - 2. Ebaluazioa (2019-2020) -percent-es
                g = coursename + "-" + courselang + "-" + courselang + group
                grouptitle = H(stylename=h3style,
                               text=translation[group][lang],
                               outlinelevel=3)
                textdoc.text.addElement(grouptitle)
                blankline = P(text="")
                textdoc.text.addElement(blankline)
                for diagramtype in [mean, percent]:  #,name2]:
                    p = P()
                    textdoc.text.addElement(p)
                    img_path = path + g + diagramtype
                    href = textdoc.addPicture(img_path)
                    f = Frame(name=group + diagramtype,
                              anchortype="paragraph",
                              width="17cm",
                              height="7.5cm",
                              zindex="0")
                    p.addElement(f)
                    img = Image(href=href,
                                type="simple",
                                show="embed",
                                actuate="onLoad")
                    f.addElement(img)
            else:
                groupPage(group, lang)
Пример #14
0
def odpRender(dic_slides_odp, nomePrj):
    lista_slides = dic_slides_odp.keys()
    lista_slides.sort()
    
    manualODP = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="MyLayout")
    manualODP.automaticstyles.addElement(pagelayout)
    pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt",
        pageheight="600pt", printorientation="landscape"))
  
    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    titlestyle = Style(name="MyMaster-title", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="42pt"))
    titlestyle.addElement(GraphicProperties(fillcolor="#ffffff", stroke="none"))
    manualODP.styles.addElement(titlestyle)

    # Style for the text frame of the page
    textostyle = Style(name="standard", family="graphic")
    textostyle.addElement(ParagraphProperties(textalign="left"))
    textostyle.addElement(TextProperties(attributes={"fontsize":"24pt" }))
    textostyle.addElement(GraphicProperties(fillcolor="#ffffff", stroke="none"))
    manualODP.styles.addElement(textostyle)

    # Style for the photo frame
    photostyle = Style(name="MyMaster-photo", family="presentation")
    manualODP.styles.addElement(photostyle)
  
    # Create automatic transition
    dpstyle = Style(name="dp1", family="drawing-page")
    dpstyle.addElement(DrawingPageProperties(transitiontype="automatic",
       transitionstyle="move-from-top", duration="PT2S"))
    manualODP.automaticstyles.addElement(dpstyle)
  
    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout)
    manualODP.masterstyles.addElement(masterpage)

    pict_dir = "./%s/img" % nomePrj
    altura_h = 540
    largura_w = 720
    base_X = 40
    base_Y = 70
    corr_Y = 60
 
    for x in lista_slides[1:]:
        titulo = dic_slides_odp[x]["titulo"]
        lista_conteudo = dic_slides_odp[x]['conteudo'].keys()
        lista_conteudo.sort()
        page = Page(stylename=dpstyle, masterpagename=masterpage)
        manualODP.presentation.addElement(page)

        titleframe = Frame(stylename=titlestyle, width="720pt", height="80pt", x="40pt", y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text=titulo))

        
        w = largura_w
        h = altura_h - base_Y  
        offsetx = base_X
        offsety = base_Y 
        espacamento_lin = 20

        for num in lista_conteudo:
           if dic_slides_odp[x]['conteudo'][num]['tipo'] == 'par':
               if w == 355:
                   offsety =  offsety + espacamento_lin


               texto_capitulo = dic_slides_odp[x]['conteudo'][num]['valor']
               textoSlide = Frame(stylename=textostyle, width="%fpt" % w, height="%fpt" % h , x="%fpt" % offsetx,   y="%fpt" % offsety)
               page.addElement(textoSlide)
               textbox = TextBox()
               textoSlide.addElement(textbox)
               textbox.addElement(P(text=texto_capitulo))

               offsety = base_Y + offsety

           if dic_slides_odp[x]['conteudo'][num]['tipo'] == 'ite':
               texto_capitulo = "  - " + dic_slides_odp[x]['conteudo'][num]['valor']
               if w == 355:
                   offsety =  offsety + espacamento_lin

               textoSlide = Frame(stylename=textostyle, width="%fpt" % w, height="%fpt" % h, x="%fpt" % offsetx, y="%fpt" % offsety)
               page.addElement(textoSlide)
               textbox = TextBox()
               textoSlide.addElement(textbox)
               textbox.addElement(P(text=texto_capitulo))
               offsety = base_Y + offsety

           if dic_slides_odp[x]['conteudo'][num]['tipo'] == 'img':
               picture = dic_slides_odp[x]['conteudo'][num]['valor'] 
               estilo_picture = dic_slides_odp[x]['conteudo'][num]['estilo'] 
               pictdata = open(pict_dir+'/'+picture).read()
               ct,w,h = getImageInfo(pictdata) # Get dimensions in pixels
               offsetx = base_X
               w = largura_w
               h = altura_h - offsety 
               if estilo_picture == 'imagem_dir':
                   offsetx = 400
                   w = 355
               if estilo_picture == 'imagem_esq':
                   offsetx = 40
                   w = 355

               if estilo_picture == 'imagem_base':
                   offsety = offsety + 10


               photoframe = Frame(stylename=photostyle, width="%fpt" % w, height="%fpt" % h, x="%fpt" % offsetx, y="%fpt" % offsety)
               page.addElement(photoframe)
               href = manualODP.addPicture(pict_dir + "/" + picture)
               photoframe.addElement(Image(href=href))
               # corrige para posicionar o texto que existe na página
               # observando se imagem_full ou não
               if estilo_picture <> 'imagem_base':
                   if offsetx == 40 :
                       offsetx = 400
                   else:
                       offsetx = 40
               offsety = base_Y + offsety

    manualODP.save("%s/t%s" % (nomePrj,nomePrj),  True)





    return
Пример #15
0
        'D': ['Batx.2H', 'Batx.2I']
    }
})

courses = [
    '1 ESO', '2 ESO', '2º PMAR', '3 ESO', '3º PMAR', '4 ESO', '1º Bach.',
    '2º Bach.'
]
#courses = ['2º Bach.']

for k in courses:
    coursePage(k, coursegroups[k], lang)

title = H(stylename=h1style, text="Promoción", outlinelevel=1)
textdoc.text.addElement(title)
for k in courses:
    p = P()
    textdoc.text.addElement(p)
    img_path = path + k + "-allgroupsprom.png"
    href = textdoc.addPicture(img_path)
    f = Frame(name=k,
              anchortype="paragraph",
              width="17cm",
              height="7.5cm",
              zindex="0")
    p.addElement(f)
    img = Image(href=href, type="simple", show="embed", actuate="onLoad")
    f.addElement(img)

textdoc.save(period + year + "/report-" + period + year + "-" + lang + ".odt")
Пример #16
0
def groupPage(group, lang):
    grouptitle = H(stylename=h3style, text=group, outlinelevel=3)
    textdoc.text.addElement(grouptitle)
    blankline = P(text="")
    textdoc.text.addElement(blankline)

    if td != '':
        table = Table()
        table.addElement(TableColumn(numbercolumnsrepeated=2))
        headers = [
            translation['part'][lang], '2 ' + translation['period'][lang]
        ]  #,"2. Ebaluazioa","Azken Ebaluazioa"]
        tr = TableRow()
        table.addElement(tr)
        for val in headers:
            tc = TableCell(stylename="Table")
            tr.addElement(tc)
            p = P(stylename=tableheaders, text=val)
            tc.addElement(p)
        #f = [["garbitasuna",3,6],["materiala",6,8],["Adostasuna", "Ez konforme","konforme"],["Harremanak1",7,8],["Harremanak2",6,7],["Adostasuna", "konforme","konforme"]]
        g = group.replace(". ", "")
        g = g.replace("º ", "")
        g = g.replace(".", "")
        g = g.replace("º", "")
        g = g.replace("° ", "")
        g = g.replace("°", "")
        g = g.replace(" ", "")
        g = g.replace("Bach1", "5")
        g = g.replace("Bach2", "6")
        g = g.replace("Batx1", "5")
        g = g.replace("Batx2", "6")
        f = td[g]
        for line in f:
            if "group" in line:  #FIXME: If not all group tables contain a row with the group name (also in text header...)
                continue
            tr = TableRow()
            table.addElement(tr)
            for i, val in enumerate(line):
                if i == 0:
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontents, text=translation[val][lang])
                elif val == "EzKonforme":
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontentscenterred,
                          text=translation[val][lang])
                elif val == "Konforme":
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    p = P(stylename=tablecontentscenter,
                          text=translation[val][lang])
                else:
                    tc = TableCell(stylename="Table")
                    tr.addElement(tc)
                    if isinstance(val, numbers.Number):
                        val = round(val, 1)
                    p = P(stylename=tablecontentscenter, text=val)
                tc.addElement(p)

        textdoc.text.addElement(table)

        blankline = P(text="")
        textdoc.text.addElement(blankline)
    if lang == "eu":
        subjectsp = P(text="%70 baino gainditu gutxiago duten ikasgaiak:")
    else:
        subjectsp = P(text="Asignaturas con menos del %70 de aprobados:")
    textdoc.text.addElement(subjectsp)
    blankline = P(text="")
    textdoc.text.addElement(blankline)
    textList = List(stylename="L1")

    file = path + "ehunekoak-" + period + "-" + year + "-" + group + ".csv"
    with open(file, 'r', encoding="UTF-8") as results:
        reader = csv.reader(results)
        headers = next(reader, None)  # get first row with headers
        for row in reader:
            if float(row[1]) < 70 and row[0] != "All":
                item = ListItem()
                if lang == "eu":
                    item.addElement(
                        P(text=row[0] + ": " + "{:.2f}".format(float(row[1])) +
                          "%"))
                else:
                    item.addElement(
                        P(text=ikasgai[row[0]] + ": " +
                          "{:.2f}".format(float(row[1])) + "%"))
                textList.addElement(item)
                textdoc.text.addElement(textList)

    breakpage = P(stylename=withbreak, text="")
    textdoc.text.addElement(breakpage)

    for diagramtype in [pie, percent]:  #,name2]:
        p = P()
        textdoc.text.addElement(p)
        img_path = path + group + diagramtype
        href = textdoc.addPicture(img_path)
        f = Frame(name=group + diagramtype,
                  anchortype="paragraph",
                  width="17cm",
                  height="7.5cm",
                  zindex="0")
        p.addElement(f)
        img = Image(href=href, type="simple", show="embed", actuate="onLoad")
        f.addElement(img)
Пример #17
0
def process_user_image_files(emailaddr):
    pagewidth = 800
    pageheight = 600
    logging.debug("cur_path %s" % (os.path.realpath('.'),) )
    odpfile = 'frieda_%s_%s.odp' % (emailaddr, time.strftime('%b_%d_%Y_%I%M%P'))
    ppt_content = []

    file_list = []
    for wroot, wsubdir, wfiles in os.walk('.'):
        wfiles = sort_files_by_time(wfiles, wroot)
        wsubdir = sort_files_by_time(wsubdir, wroot)
        cnt = 0
        for f in wfiles:
            cnt += 1
            file_list.append(os.path.join(wroot, f))
        if cnt != 0:
            wroot2 = '/' if len(wroot) < 2 else wroot[1:]
            ppt_content.append((wroot2, cnt))

    logging.debug('file_list: %r' % file_list)
    doc = OpenDocumentPresentation()
    pagelayout = PageLayout(name="MyLayout")
    pagelayout.addElement(PageLayoutProperties(backgroundcolor="#000000", margin="0pt", pagewidth="%dpt" %pagewidth,
                                               pageheight="%dpt" % pageheight, printorientation="landscape"))
    doc.automaticstyles.addElement(pagelayout)
    photostyle = Style(name="RadTeaching-photo", family="presentation")
    doc.styles.addElement(photostyle)
    dstyle = Style(name="d", family="drawing-page")
    dstyle.addElement(GraphicProperties(fillcolor="#000000"))
    dstyle.addElement(DrawingPageProperties(fill=True,
                                            fillcolor="#000000"))
    doc.automaticstyles.addElement(dstyle)


    masterpage = MasterPage(name="RadTeaching", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)
    images_added = 0
    # os.chdir(subdir)
    for picture in file_list:
        try:
            pictdata = open(picture).read()
            logging.debug("Adding %s" % (picture))
        except:
            logging.debug("Skipping %s" % (picture))
            continue
        ct,w,h = getImageInfoFileName(picture)
        if ct == 'not image':
            if picture[-4:] == '.dcm':
                png_picture = picture.replace('.dcm','.png')
                logging.debug("Converting %s to %s" % (picture, png_picture) )
                run_command(""" dcmj2pnm +on +Wi 1 %s %s """ % (picture, png_picture))
                picture = png_picture
                ct,w,h = getImageInfoFileName(picture)

        if ct not in ("jpeg", "jpg", "tiff", "png", "bmp", "gif", "tif"):
            logging.debug("Skipping %s unrecognized type %s" % (picture,ct) )
            continue
        if ct == "tiff" or ct == "tif":
            png_picture = picture.replace(".tiff",".tif").replace(".tif", ".png")
            logging.debug("Converting %s to %s" % (picture, png_picture))
            img = PythonMagick.Image()
            img.read(picture)
            if img.depth() > 8: # powerpoint can't handle 16 bit TIFF images.
                img.write(png_picture)
                del img
                picture = png_picture
                ct,w,h = getImageInfoFileName(picture)

        images_added += 1
        if w*pageheight > h*pagewidth: #check if width or height is limit to zooming
            h = float(h) * (pagewidth-2.0)/float(w)
            w = pagewidth - 2.0
        else:
            w = float(w)*(pageheight-2.0) / float(h)
            h = pageheight -2.0

        page = Page(stylename=dstyle, masterpagename=masterpage)
        doc.presentation.addElement(page)

        offsetx = (pagewidth - w)/2.0
        offsety = (pageheight - h)/2.0
        photoframe = Frame(stylename=photostyle, width='%fpt' % w, height='%fpt' % h,
                           x = '%fpt' % offsetx, y='%fpt' % offsety)
        page.addElement(photoframe)
        href = doc.addPicture(picture)
        photoframe.addElement(Image(href=href))

    if images_added > 0:
        logging.debug('Saving ODP as %s/%s' % (os.path.realpath('.'), odpfile))
        doc.save(odpfile)
    return (odpfile, images_added, ppt_content) if images_added > 0 else (False, 0, None)
Пример #18
0
"""
    <text:h text:outline-level="1">An Image</text:h>
     <text:p>
       <draw:frame draw:name="graphics1" text:anchor-type="paragraph"
         svg:width="5in"
         svg:height="6.6665in" draw:z-index="0">
         <draw:image xlink:href="Pictures/campanile_fog.jpg" xlink:type="simple"
           xlink:show="embed"
           xlink:actuate="onLoad"/>
       </draw:frame>
     </text:p>
"""

textdoc.text.addElement(H(outlinelevel=1,text='An Image'))
p = P()
textdoc.text.addElement(p)
# add the image
# img_path is the local path of the image to include
img_path = r'..\data\img\metadator.png';
#img_path = 'D:\Document\PersonalInfoRemixBook\examples\ch17\campanile_fog.jpg'
href = textdoc.addPicture(img_path)
f = Frame(name="graphics1", anchortype="paragraph", width="5in", height="6.6665in",
zindex="0")
p.addElement(f)
img = Image(href=href, type="simple", show="embed", actuate="onLoad")
f.addElement(img)



# save the document
textdoc.save(fname)
Пример #19
0
def Page_Rect_get_Text_odf(doc, page_num, rects, hierarchy, Xrects, output,
                           style_p, style_i, img_quality, col):
    page = doc[page_num]
    words = page.getText("words")
    output.text.addElement(P(stylename=style_p, text="_" * 60))
    if col == 1 or col == 2:
        output.text.addElement(
            P(stylename=style_p, text=f"page {page_num+1} - column {col}"))
    else:
        output.text.addElement(P(stylename=style_p, text=f"page {page_num+1}"))
    for i in range(rects.shape[0]):
        if hierarchy[i, 3] == -1:
            rect = Rect(rects[i, 0], rects[i, 1], rects[i, 2], rects[i, 3])
            allwords = [w for w in words if Rect(w[:4]) in rect]
            # iterate over all rects to exclude
            mywords = []
            for w in allwords:
                exclude = 0
                for Xrect in Xrects:
                    xg = (w[0] + w[2]) / 2
                    yg = (w[1] + w[3]) / 2
                    if Rect(Xrect).contains((xg, yg)):
                        exclude = 1
                if exclude == 0:
                    mywords.append(w)

            mywords.sort(key=itemgetter(3,
                                        0))  # sort by y1, x0 of the word rect
            group = groupby(mywords, key=itemgetter(3))

            output.text.addElement(P(stylename=style_p, text=""))
            out_text = P(stylename=style_p, text="")
            for y1, gwords in group:
                out_text.addText(" ".join(w[4]
                                          for w in gwords).replace("\n", " "))
                out_text.addText(" ")
            output.text.addElement(out_text)
        if hierarchy[i, 3] != -1:

            clip = Rect(rects[i, 0], rects[i, 1], rects[i, 2], rects[i, 3])
            #taking into account quality
            img_qual = img_quality / 50.

            pix = page.getPixmap(matrix=Matrix(img_qual, img_qual), clip=clip)

            name_image = f"Pictures/image-{page.number}-{col}{i}.png"
            pix_png = pix.getPNGData()
            h = pix.height / pix.xres
            w = pix.width / pix.yres
            #if quality is larger than 2 keep the frame the same as if it was 2
            h *= 2 / img_qual
            w *= 2 / img_qual
            #if image is too small (h<20px) it is probably an artifact
            #so do not print it
            if pix.height * 2 / img_qual > 20:
                output.text.addElement(P(stylename=style_p, text=""))
                out_img = P()
                frame = Frame(stylename=style_i,
                              width=f"{w}in",
                              height=f"{h}in",
                              anchortype="paragraph")
                href = output.addPicture(name_image,
                                         mediatype="png",
                                         content=pix_png)  #
                frame.addElement(Image(href=f"./{href}"))
                out_img.addElement(frame)
                output.text.addElement(out_img)
    return output
Пример #20
0
        doc.presentation.addElement(page)

        note = Notes(stylename=dpstyle)
        page.addElement(note)
        noteframe = Frame(stylename=prstyle,
                          layer="layout",
                          width="16.799cm",
                          height="13.364cm",
                          x="2.1cm",
                          y="14.107cm",
                          placeholder="true",
                          classname="notes")
        note.addElement(noteframe)
        notetextbox = TextBox()
        notetextbox.addElement(P(text=notes[i] if (i in notes) else ""))
        noteframe.addElement(notetextbox)

        photoframe = Frame(stylename=photostyle,
                           width=str(w) + "pt",
                           height=str(h) + "pt",
                           x="0pt",
                           y="0pt")
        page.addElement(photoframe)
        href = doc.addPicture(fname)
        photoframe.addElement(Image(href=href))

        i += 1

    doc.save(args["<output>"])
    shutil.rmtree(pict_dir)
Пример #21
0
def create_presentation(sura_number, outputfile, start=None, end=None, arabic_font="Calibri"):
    suras = load_suras("quran-uthmani.xml", "shakir_table.csv")
    doc = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="MyLayout")
    dp = Style(name="dp1", family="drawing-page")
    dp.addElement(DrawingPageProperties(backgroundvisible="true", backgroundobjectsvisible="true"))
    doc.automaticstyles.addElement(pagelayout)
    doc.automaticstyles.addElement(dp)
    pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt",
        pageheight="600pt", printorientation="landscape", backgroundcolor="#000000"))

    ls = LayerSet()
    ls.addElement(Layer(name="layout"))
    ls.addElement(Layer(name="background"))
    ls.addElement(Layer(name="backgroundobjects"))
    ls.addElement(Layer(name="title"))
    doc.masterstyles.addElement(ls)

    titlestyle = Style(name="MyMaster-title", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="60pt", fontsizeasian="96pt", fontsizecomplex="96pt", color="#ffffff", fontfamily="Calibri", fontfamilyasian=arabic_font, fontfamilycomplex=arabic_font))
    titlestyle.addElement(GraphicProperties(fillcolor="#000000"))
    doc.styles.addElement(titlestyle)
    masterstyle = Style(name="MyMaster-dp", family="drawing-page")
    masterstyle.addElement(DrawingPageProperties(fill="solid", fillcolor="#000000", backgroundsize="border", fillimagewidth="0cm", fillimageheight="0cm"))
    doc.styles.addElement(masterstyle)
    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout, stylename=masterstyle)

    doc.masterstyles.addElement(masterpage)
    # add title page
    page = Page(stylename=dp, masterpagename=masterpage)
    doc.presentation.addElement(page)
    titleframe = Frame(stylename=titlestyle, width="800pt", height="300pt", x="0pt", y="200pt")
    page.addElement(titleframe)
    textbox = TextBox()
    titleframe.addElement(textbox)
    titletext = "Sura %s" % (SURA_NAMES[sura_number],)
    if start:
        titletext += "\nAyat %s to %s" % (start, end)
    textbox.addElement(P(stylename=titlestyle, text=titletext))

    if sura_number != 9 and not (sura_number == 1 and (start is None or int(start) == 1)):
        # add bismillah
        page = Page(stylename=dp, masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=titlestyle, width="800pt", height="270pt", x="0pt", y="30pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        ayat = suras[1][1]
        textbox.addElement(P(stylename=titlestyle, text=ayat["arabic"]))
        secondframe = Frame(stylename=titlestyle, width="800pt", height="270pt", x="0pt", y="300pt")
        page.addElement(secondframe)
        secondbox = TextBox()
        secondframe.addElement(secondbox)
        secondbox.addElement(P(stylename=titlestyle, text=ayat["english"]))        
    for number, ayat in suras[sura_number].iteritems():
        if start is None or (number >= int(start) and number <= int(end)):
            page = Page(stylename=dp, masterpagename=masterpage)
            doc.presentation.addElement(page)
            titleframe = Frame(stylename=titlestyle, width="800pt", height="270pt", x="0pt", y="30pt")
            page.addElement(titleframe)
            textbox = TextBox()
            titleframe.addElement(textbox)
            textbox.addElement(P(stylename=titlestyle, text=ayat["arabic"]))
            secondframe = Frame(stylename=titlestyle, width="800pt", height="270pt", x="0pt", y="300pt")
            page.addElement(secondframe)
            secondbox = TextBox()
            secondframe.addElement(secondbox)
            secondbox.addElement(P(stylename=titlestyle, text=ayat["english"]))
    doc.save(outputfile)
Пример #22
0
def do_job(job):
    """Do something"""
    warnings = get_warnings(job['sts'], job['ets'], job['wfo'], job['wtype'])

    mydir = "%s/%s" % (TMPDIR, job['jobid'])
    if not os.path.isdir(mydir):
        os.makedirs(mydir)
    os.chdir(mydir)

    basefn = "%s-%s-%s-%s-%s" % (job['wfo'], job['wtype'].replace(
        ",", "_"), job['radar'], job['sts'].strftime("%Y%m%d%H"),
                                 job['ets'].strftime("%Y%m%d%H"))
    outputfile = "%s.odp" % (basefn, )

    doc = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="MyLayout")
    doc.automaticstyles.addElement(pagelayout)
    pagelayout.addElement(
        PageLayoutProperties(margin="0pt",
                             pagewidth="800pt",
                             pageheight="600pt",
                             printorientation="landscape"))

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    titlestyle = Style(name="MyMaster-title2", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="34pt"))
    titlestyle.addElement(GraphicProperties(fillcolor="#ffff99"))
    doc.styles.addElement(titlestyle)

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    indexstyle = Style(name="MyMaster-title", family="presentation")
    indexstyle.addElement(ParagraphProperties(textalign="center"))
    indexstyle.addElement(TextProperties(fontsize="28pt"))
    indexstyle.addElement(GraphicProperties(fillcolor="#ffffff",
                                            stroke="none"))
    doc.styles.addElement(indexstyle)

    # Style for the photo frame
    photostyle = Style(name="MyMaster-photo", family="presentation")
    doc.styles.addElement(photostyle)

    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)

    dpstyle = Style(name="dp1", family="drawing-page")
    # dpstyle.addElement(DrawingPageProperties(transitiontype="automatic",
    #   transitionstyle="move-from-top", duration="PT5S"))
    doc.automaticstyles.addElement(dpstyle)

    # Title slide
    page = Page(masterpagename=masterpage)
    doc.presentation.addElement(page)
    frame = Frame(stylename=indexstyle,
                  width="720pt",
                  height="500pt",
                  x="40pt",
                  y="10pt")
    page.addElement(frame)
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="IEM Raccoon Report"))

    frame = Frame(stylename=indexstyle,
                  width="720pt",
                  height="500pt",
                  x="40pt",
                  y="150pt")
    page.addElement(frame)
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="WFO: %s" % (job['wfo'], )))
    textbox.addElement(
        P(text=("Radar: %s Product: %s"
                "") % (job['radar'], job['nexrad_product'])))
    textbox.addElement(P(text="Phenomenas: %s" % (job['wtype'], )))
    textbox.addElement(
        P(text="Start Time: %s UTC" % (job['sts'].strftime("%d %b %Y %H"), )))
    textbox.addElement(
        P(text="End Time: %s UTC" % (job['ets'].strftime("%d %b %Y %H"), )))
    textbox.addElement(P(text=""))
    textbox.addElement(P(text="Raccoon Version: %s" % (__REV__, )))
    textbox.addElement(
        P(text="Generated on: %s" %
          (datetime.datetime.utcnow().strftime("%d %b %Y %H:%M %Z"))))
    textbox.addElement(P(text=""))
    textbox.addElement(
        P(text="Bugs/Comments/Yelling?: daryl herzmann [email protected]"))

    i = 0
    for warning in warnings:
        # Make Index page for the warning
        page = Page(masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=indexstyle,
                           width="700pt",
                           height="500pt",
                           x="10pt",
                           y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(
            P(text="%s.O.NEW.K%s.%s.W.%04i" %
              (job['sts'].year, job['wfo'], warning['phenomena'],
               warning['eventid'])))
        textbox.addElement(
            P(text="Issue: %s UTC" %
              (warning['issue'].strftime("%d %b %Y %H:%M"), )))
        textbox.addElement(
            P(text="Expire: %s UTC" %
              (warning['expire'].strftime("%d %b %Y %H:%M"), )))
        textbox.addElement(
            P(text="Poly Area: %.1f sq km (%.1f sq mi) [%.1f%% vs County]" %
              (warning['polyarea'], warning['polyarea'] * 0.386102,
               warning['polyarea'] / warning['countyarea'] * 100.0)))
        textbox.addElement(
            P(text="County Area: %.1f square km (%.1f square miles)" %
              (warning['countyarea'], warning['countyarea'] * 0.386102)))

        url = ("http://iem.local/GIS/radmap.php?"
               "layers[]=places&layers[]=legend&layers[]=ci&layers[]=cbw"
               "&layers[]=sbw&layers[]=uscounties&layers[]=bufferedlsr"
               "&lsrbuffer=15")
        url += "&vtec=%s.O.NEW.K%s.%s.W.%04i" % (job['sts'].year, job['wfo'],
                                                 warning['phenomena'],
                                                 warning['eventid'])

        cmd = "wget -q -O %i.png '%s'" % (i, url)
        os.system(cmd)
        photoframe = Frame(stylename=photostyle,
                           width="480pt",
                           height="360pt",
                           x="160pt",
                           y="200pt")
        page.addElement(photoframe)
        href = doc.addPicture("%i.png" % (i, ))
        photoframe.addElement(Image(href=href))
        i += 1

        times = []
        now = warning['issue']
        while now < warning['expire']:
            times.append(now)
            now += datetime.timedelta(minutes=15)
        times.append(warning['expire'] - datetime.timedelta(minutes=1))

        for now in times:
            page = Page(stylename=dpstyle, masterpagename=masterpage)
            doc.presentation.addElement(page)
            titleframe = Frame(stylename=titlestyle,
                               width="720pt",
                               height="56pt",
                               x="40pt",
                               y="10pt")
            page.addElement(titleframe)
            textbox = TextBox()
            titleframe.addElement(textbox)
            textbox.addElement(
                P(text="%s.W.%04i Time: %s UTC" %
                  (warning['phenomena'], warning['eventid'],
                   now.strftime("%d %b %Y %H%M"))))

            if job['nexrad_product'] == 'N0U':
                if now < SUPER_RES:
                    n0qn0r = 'N0V'
                else:
                    n0qn0r = 'N0U'
            else:
                if now < SUPER_RES:
                    n0qn0r = 'N0R'
                else:
                    n0qn0r = 'N0Q'

            url = "http://iem.local/GIS/radmap.php?"
            url += "layers[]=ridge&ridge_product=%s&ridge_radar=%s&" % (
                n0qn0r, job['radar'])
            url += "layers[]=sbw&layers[]=sbwh&layers[]=uscounties&"
            url += "layers[]=lsrs&ts2=%s&" % ((
                now + datetime.timedelta(minutes=15)).strftime("%Y%m%d%H%M"), )
            url += "vtec=%s.O.NEW.K%s.%s.W.%04i&ts=%s" % (
                job['sts'].year, job['wfo'], warning['phenomena'],
                warning['eventid'], now.strftime("%Y%m%d%H%M"))

            cmd = "wget -q -O %i.png '%s'" % (i, url)
            os.system(cmd)
            photoframe = Frame(stylename=photostyle,
                               width="640pt",
                               height="480pt",
                               x="80pt",
                               y="70pt")
            page.addElement(photoframe)
            href = doc.addPicture("%i.png" % (i, ))
            photoframe.addElement(Image(href=href))
            i += 1

    doc.save(outputfile)
    del doc
    cmd = "unoconv -f ppt %s" % (outputfile, )
    subprocess.call(cmd, shell=True)
    pptfn = "%s.ppt" % (basefn, )
    print("Generated %s with %s slides" % (pptfn, i))
    if os.path.isfile(pptfn):
        print('...copied to webfolder')
        shutil.copyfile(pptfn, "/mesonet/share/pickup/raccoon/%s" % (pptfn, ))
        # Cleanup
        os.chdir(TMPDIR)
        subprocess.call("rm -rf %s" % (job['jobid'], ), shell=True)
    else:
        print("Uh oh, no output file, lets kill soffice.bin")
        subprocess.call("pkill --signal 9 soffice.bin", shell=True)
        add_job(job)
Пример #23
0
def do_job(job):

    warnings = get_warnings(job['sts'], job['ets'], job['wfo'], job['wtype'])

    os.makedirs("/tmp/%s" % (job['jobid'],))
    os.chdir("/tmp/%s" % (job['jobid'],))
    
    basefn = "%s-%s-%s-%s-%s" % (job['wfo'], job['wtype'].replace(",", "_"), 
                                 job['radar'], job['sts'].strftime("%Y%m%d%H"),
                                      job['ets'].strftime("%Y%m%d%H"))
    outputfile = "%s.odp" % (basefn,)

    doc = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="MyLayout")
    doc.automaticstyles.addElement(pagelayout)
    pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt",
        pageheight="600pt", printorientation="landscape"))

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    titlestyle = Style(name="MyMaster-title2", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="34pt"))
    titlestyle.addElement(GraphicProperties(fillcolor="#ffff99"))
    doc.styles.addElement(titlestyle)

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    indexstyle = Style(name="MyMaster-title", family="presentation")
    indexstyle.addElement(ParagraphProperties(textalign="center"))
    indexstyle.addElement(TextProperties(fontsize="28pt"))
    indexstyle.addElement(GraphicProperties(fillcolor="#ffffff",
                                            stroke="none"))
    doc.styles.addElement(indexstyle)

    # Style for the photo frame
    photostyle = Style(name="MyMaster-photo", family="presentation")
    doc.styles.addElement(photostyle)

    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)

    dpstyle = Style(name="dp1", family="drawing-page")
    #dpstyle.addElement(DrawingPageProperties(transitiontype="automatic",
    #   transitionstyle="move-from-top", duration="PT5S"))
    doc.automaticstyles.addElement(dpstyle)
    
    # Title slide
    page = Page(masterpagename=masterpage)
    doc.presentation.addElement(page)
    frame = Frame(stylename=indexstyle, width="720pt", height="500pt", 
                  x="40pt", y="10pt")
    page.addElement( frame )
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="IEM Raccoon Report"))
    
    frame = Frame(stylename=indexstyle, width="720pt", height="500pt", 
                  x="40pt", y="150pt")
    page.addElement( frame )
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="WFO: %s" % (job['wfo'],)))
    textbox.addElement(P(text="Radar: %s Product: %s" % (job['radar'], job['nexrad_product'])))
    textbox.addElement(P(text="Phenomenas: %s" % (job['wtype'], )))
    textbox.addElement(P(text="Start Time: %s UTC" % (job['sts'].strftime("%d %b %Y %H"),)))
    textbox.addElement(P(text="End Time: %s UTC" % (job['ets'].strftime("%d %b %Y %H"),)))
    textbox.addElement(P(text=""))
    textbox.addElement(P(text="Raccoon Version: %s" % (__REV__,)))
    textbox.addElement(P(text="Generated on: %s" % (
                                    datetime.datetime.utcnow().strftime("%d %b %Y %H:%M %Z"))))
    textbox.addElement(P(text=""))
    textbox.addElement(P(text="Bugs/Comments/Yelling?: daryl herzmann [email protected]"))
    
    
    i = 0
    for warning in warnings:
        # Make Index page for the warning
        page = Page(masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=indexstyle, width="700pt", height="500pt", 
                       x="10pt", y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text="%s.O.NEW.K%s.%s.W.%04i" % ( 
                                    job['sts'].year, job['wfo'],
                                warning['phenomena'],warning['eventid'])))
        textbox.addElement(P(text="Issue: %s UTC" % ( 
                                    warning['issue'].strftime("%d %b %Y %H:%M"),)))
        textbox.addElement(P(text="Expire: %s UTC" % ( 
                                    warning['expire'].strftime("%d %b %Y %H:%M"),)))
        textbox.addElement(P(text="Poly Area: %.1f sq km (%.1f sq mi) [%.1f%% vs County]" % ( 
                                    warning['polyarea'], warning['polyarea'] * 0.386102,
                                    warning['polyarea'] / warning['countyarea'] * 100.0)))
        textbox.addElement(P(text="County Area: %.1f square km (%.1f square miles)" % ( 
                                    warning['countyarea'], warning['countyarea'] * 0.386102)))
        
        url = "http://iem21.local/GIS/radmap.php?"
        url += "layers[]=places&layers[]=legend&layers[]=ci&layers[]=cbw&layers[]=sbw"
        url += "&layers[]=uscounties&layers[]=bufferedlsr&lsrbuffer=15"
        url += "&vtec=%s.O.NEW.K%s.%s.W.%04i" % ( job['sts'].year, job['wfo'],
                                    warning['phenomena'],warning['eventid'])
        
        cmd = "wget -q -O %i.png '%s'" % (i, url)
        os.system(cmd)
        photoframe = Frame(stylename=photostyle, width="480pt", 
                               height="360pt", x="160pt", y="200pt")
        page.addElement(photoframe)
        href = doc.addPicture("%i.png" % (i,))
        photoframe.addElement(Image(href=href))
        i += 1
        
        times = []
        now = warning['issue']
        while now < warning['expire']:
            times.append( now )
            now += datetime.timedelta(minutes=15)
        times.append( warning['expire'] - datetime.timedelta(minutes=1))
        
        for now in times:    
            page = Page(stylename=dpstyle, masterpagename=masterpage)
            doc.presentation.addElement(page)
            titleframe = Frame(stylename=titlestyle, width="720pt", height="56pt", 
                           x="40pt", y="10pt")
            page.addElement(titleframe)
            textbox = TextBox()
            titleframe.addElement(textbox)
            textbox.addElement(P(text="%s.W.%04i Time: %s UTC" % ( 
                                    warning['phenomena'],warning['eventid'],
                                    now.strftime("%d %b %Y %H%M"))))
            
            if job['nexrad_product'] == 'N0U':
                if now < SUPER_RES:
                    n0qn0r = 'N0V'
                else:
                    n0qn0r = 'N0U'
            else:
                if now < SUPER_RES:
                    n0qn0r = 'N0R'
                else:
                    n0qn0r = 'N0Q'
            
            url = "http://iem21.local/GIS/radmap.php?"
            url += "layers[]=ridge&ridge_product=%s&ridge_radar=%s&" % (n0qn0r, 
                                                                job['radar'])
            url += "layers[]=sbw&layers[]=sbwh&layers[]=uscounties&"
            url += "layers[]=lsrs&ts2=%s&" % (
                    (now + datetime.timedelta(minutes=15)).strftime("%Y%m%d%H%M"),)
            url += "vtec=%s.O.NEW.K%s.%s.W.%04i&ts=%s" % ( job['sts'].year, job['wfo'],
                                    warning['phenomena'],warning['eventid'],
                                    now.strftime("%Y%m%d%H%M"))

            cmd = "wget -q -O %i.png '%s'" % (i, url)
            os.system(cmd)
            photoframe = Frame(stylename=photostyle, width="640pt", 
                               height="480pt", x="80pt", y="70pt")
            page.addElement(photoframe)
            href = doc.addPicture("%i.png" % (i,))
            photoframe.addElement(Image(href=href))
            i += 1

    doc.save(outputfile)
    del doc
    cmd = "unoconv -f ppt %s" % (outputfile,)
    os.system( cmd )
    print "%s.ppt" % (basefn,)
    if os.path.isfile("%s.ppt" % (basefn,)):
        print 'Here!'
        shutil.copyfile("%s.ppt" % (basefn,), "/mesonet/share/pickup/raccoon/%s.ppt" % (basefn,))
Пример #24
0
textStyleB = Style(name="textstyleB", family="paragraph")
tpB = TextProperties(fontsize="16pt", fontfamily="diluvienne")
textStyleB.addElement(tpB)

frameA = Frame(stylename=graphicStyleA, height="15cm", width="10cm")
frameB = Frame(stylename=graphicStyleB, height="10cm", width="15cm")

doc.styles.addElement(graphicStyleA)
doc.styles.addElement(textStyleA)

doc.styles.addElement(graphicStyleB)
doc.styles.addElement(textStyleB)

textboxA = TextBox()
textboxB = TextBox()

frameA.addElement(textboxA)
frameB.addElement(textboxB)

pA = P(stylename="textstyleA", text="aaaaaah")
pB = P(stylename="textstyleB", text="bbbbbah")

textboxA.addElement(pA)
textboxB.addElement(pB)

doc.text.addElement(frameA)
doc.text.addElement(frameB)

doc.save("ab", True)
Пример #25
0
    def opIn(self, opt: Union[float, str, "odf.element.Element", List, "AQOdsImage"]):
        """
        Add options to the line.

        @param opt. Line options, each cell ends with the value assignment
        """

        from odf.text import P, Span  # type: ignore
        from odf.draw import Frame, Image  # type: ignore

        if isinstance(opt, float):
            if self.fix_precision_ is not None:
                opt = "%s" % round(opt, self.fix_precision_)
            else:
                opt = "%s" % opt
        if isinstance(opt, str):  # Último paso
            cell, style = self.__newCell__()

            if self.style_cell_text_:
                text_elem = P(text="")
                txt_ = Span(stylename=self.style_cell_text_, text=opt)
                text_elem.addElement(txt_)
            else:
                text_elem = P(text=opt)

            self.sheet_.spread_sheet_parent_.automaticstyles.addElement(style)
            cell.addElement(text_elem)
            self.cells_list_.append(cell)
            self.fix_precision_ = None
            self.style_cell_text_ = None

        else:
            if isinstance(opt, list):  # Si es lista , Insertamos todos los parámetros uno a uno
                for l in opt:
                    self.opIn(l)

            elif isinstance(opt, AQOdsImage):

                href = self.sheet_.spread_sheet_parent_.addPictureFromFile(opt.link_)
                cell, style = self.__newCell__()

                # p = P()
                frame = Frame(
                    width="%spt" % opt.width_,
                    height="%spt" % opt.height_,
                    x="%spt" % opt.x_,
                    y="%spt" % opt.y_,
                )
                frame.addElement(Image(href=href))
                # p.addElement(frame)
                cell.addElement(frame)
                self.cells_list_.append(cell)
                # self.coveredCell()
                # self.opIn(href)
                # print("FIXME:: Vacio", href)
            elif isinstance(opt, odf.element.Element):
                if opt.tagName in ("style:paragraph-properties", "style:table-cell-properties"):
                    import copy

                    prop = copy.copy(opt)
                    self.property_cell_.append(prop)
                elif opt.tagName == "style:style":
                    self.sheet_.spread_sheet_parent_.automaticstyles.addElement(opt)
                    self.style_cell_text_ = opt
                else:
                    logger.warning("%s:Parámetro desconocido %s", __name__, opt.tagName)
Пример #26
0
        if w > 720:
            h = float(h) * 720.0 / float(w)
            w = 720.0
        if h > 540.0:
            w = float(w) * 540.0 / float(h)
            h = 540.0

        page = Page(stylename=dpstyle, masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=titlestyle,
                           width="720pt",
                           height="56pt",
                           x="40pt",
                           y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text=picture))

        offsetx = 400.0 - w / 2.0
        photoframe = Frame(stylename=photostyle,
                           width="%fpt" % w,
                           height="%fpt" % h,
                           x="%fpt" % offsetx,
                           y="56pt")
        page.addElement(photoframe)
        href = doc.addPicture(pict_dir + "/" + picture)
        photoframe.addElement(Image(href=href))

    doc.save(outputfile)
Пример #27
0
    for picture in os.listdir(pict_dir):
        try:
            pictdata = open(pict_dir + "/" + picture).read()
        except:
            continue
        ct,w,h = getImageInfo(pictdata) # Get dimensions in pixels
        if ct != 'image/jpeg':
            continue
        if w > 720:
           h = float(h) * 720.0 / float(w)
           w = 720.0
        if h > 540.0:
           w = float(w) * 540.0 / float(h)
           h = 540.0

        page = Page(stylename=dpstyle, masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=titlestyle, width="720pt", height="56pt", x="40pt", y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text=picture))

        offsetx = 400.0 - w/2.0
        photoframe = Frame(stylename=photostyle, width="%fpt" % w, height="%fpt" % h, x="%fpt" % offsetx, y="56pt")
        page.addElement(photoframe)
        href = doc.addPicture(pict_dir + "/" + picture)
        photoframe.addElement(Image(href=href))

    doc.save(outputfile)