예제 #1
1
def reportAddendum(reportFile, listofOutputsTobeAdded, listOfComments=None):
    """
    Enables to  add figures to a report in an automated way.
    The changes intervine after the last chapter of the report.
    """
    if ".docx" in reportFile:
        document = Document(reportFile)
    else:
        raise Warning(" problem with the format of the file")
    paragraph_styles = [s for s in document.styles if s.type == WD_STYLE_TYPE.PARAGRAPH]

    postProcessingHeader = document.add_paragraph("PostProcessing", style=paragraph_styles[1])
    postProcessingText = document.add_paragraph(style=paragraph_styles[0])
    postProcessingText.add_run("\rWord format postprocessing generated through the ")
    postProcessingText.add_run("etumos ").bold = True
    postProcessingText.add_run("coupling tool\r\r")
    # document.add_heading('Outputs', level=1)
    ind = 0
    for picture in listofOutputsTobeAdded:
        document.add_picture(picture, width=Cm(7.00))
        document.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER
        newParagraph = document.add_paragraph("\r")
        newParagraph.add_run("Figure n. " + str(ind) + ":   ").bold = True
        if listOfComments != None:
            newParagraph.add_run(str(listOfComments[ind]))
        ind += 1
        newParagraph.add_run(" \r \r")
        newParagraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    reportFile = reportFile.replace(".docx", "")
    filenameToBeSaved = reportFile + "_pp.docx"
    document.save(filenameToBeSaved)
    return None
예제 #2
0
class XQHTMLParser(HTMLParser):
    def __init__(self, docfile):
        HTMLParser.__init__(self)
        self.docfile = docfile
        self.doc = Document(docfile)
        self.myclient = HTMLClient()
        self.text = ''
        self.title = False
        self.isdescription = False
        self.picList=[]
    def handle_starttag(self, tag, attrs):
        #print "Encountered the beginning of a %s tag" % tag
        self.title = False
        self.isdescription = False
        if re.match(r'h(\d)', tag):
            self.title = True 
        if tag == "img":
            if len(attrs) == 0: pass
            else:
                for (variable, value)  in attrs:
                    if variable == "src":
                        picdata = self.myclient.GetPic(value.split('!')[0])
                        if picdata == None:
                            pass
                        else:
                            pictmp = value.split('/')[-1].split('!')[0]
                            picfix = value.split('/')[-1].split('!')[-1]
                            with open(pictmp, 'wb') as pic:
                                pic.write(bytes(picdata))
                                pic.close()
                            #if os.path.getsize(pictmp) < 90000:
                            try:
                                if picfix[0:1] == 'c':
                                    self.doc.add_picture(pictmp, width=Inches(4.5))
                                else:
                                    self.doc.add_picture(pictmp)#, width=Inches(2.25))
                            except docx.image.exceptions.UnexpectedEndOfFileError as e:
                                print(e)
                            self.picList.append(pictmp)
        if tag == 'script':
            self.isdescription = True
    def handle_data(self, data):
        if self.title == True:
            if self.text != '':
                self.doc.add_paragraph(self.text)
            self.text = ''
            self.doc.add_heading(data, level=2)
        if self.isdescription == False:
            self.text += data
    def handle_endtag(self, tag):
        #if tag == 'br' or tag == 'p' or tag == 'div':
        if self.text != '':
            self.doc.add_paragraph(self.text)
            self.text = ''
    def complete(self, html):
        self.feed(html)
        self.doc.save(self.docfile)
        for item in self.picList:
            if os.path.exists(item):
                os.remove(item)
예제 #3
0
def save2Word():
    file_name = './word/'+title+'.docx'


    with open('./txt/mainContent.txt','a') as f1:
        with open('./txt/comment.txt','rb') as f2:
            f1.write(f2.read())

    with open('./txt/mainContent.txt','rb') as article_complete:

        document = Document()
        for line in article_complete:
            if len(line) == 7 or len(line) == 13 or line == '\n':continue #手动换行符暂时解决不了

            img_url = re.findall(r'(http:.*?\.jpg|http:.*?\.png|http:.*?\.gif)',line,re.S)
            line = re.sub(r'(http:.*?\.jpg|http:.*?\.png|http:.*?\.gif)','',line)
            for img in img_url:
                imgName = saveImg(img)
                if imgName != 0:
                    try:
                        document.add_picture('./img/'+imgName, width=Inches(3.25))
                    except Exception:
                         document.add_paragraph(u'图片加载失败....')
                         document.add_paragraph(img)
                else:
                    document.add_paragraph(u'图片加载失败....')
                    document.add_paragraph(img)
            document.add_paragraph(line.decode('UTF-8'))

        document.save(file_name.decode('UTF-8'))
예제 #4
0
파일: mdoc.py 프로젝트: tuling56/Python
def mdoc():
    document = Document()
    document.add_heading("Document Title", 0)

    p = document.add_paragraph("A plain paragraph having some ")
    p.add_run("bold").bold = True
    p.add_run(" and some ")
    p.add_run("italic.").italic = True

    document.add_heading("Heading, level 1", level=1)
    document.add_paragraph("Intense quote", style="IntenseQuote")

    document.add_paragraph("first item in unordered list", style="ListBullet")
    document.add_paragraph("first item in ordered list", style="ListNumber")

    document.add_picture("monty-truth.png", width=Inches(1.25))

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = "Qty"
    hdr_cells[1].text = "Id"
    hdr_cells[2].text = "Desc"
    for item in recordset:
        row_cells = table.add_row().cells
        row_cells[0].text = str(item.qty)
        row_cells[1].text = str(item.id)
        row_cells[2].text = item.desc

    document.add_page_break()

    document.save("demo.docx")
예제 #5
0
    def exportPayInfo(self):
        """ 导出出付费信息 """

        title = '%s[%s]' % (self.username, datetime.strftime(datetime.now(), "%Y-%m-%d"))
        reserveInfo = pitcher.getReserveInfo()
        c1 = reserveInfo[u'状态'] == u'未确认'
        c2 = reserveInfo[u'最后确认时间'].apply(parser.parse) > datetime.now()
        reserveInfo = reserveInfo[c1 & c2]
        document = Document()
        document.add_heading(title)
        for i, row in reserveInfo.iterrows():
            document.add_heading(u'票项%d' % (i + 1), level=1)
            document.add_paragraph(text=u'航线: ' + row[u'航线'])
            document.add_paragraph(text=u'航班时间: ' + row[u'航班时间'])
            document.add_paragraph(text=u'人数: ' + row[u'人数'])
            document.add_paragraph(text=u'金额: ' + row[u'金额'])
            document.add_paragraph(text=u'最后确认时间: ' + row[u'最后确认时间'])
            filename = tempfile.mktemp(suffix='.jpg',prefix='tmp_')
            with open(filename, 'wb') as f:
                orderNumber = pitcher.getOrderNumber(row[u'预订ID'])
                qrcode = pitcher.getWeixinPayQrcode(orderNumber)
                f.write(qrcode)
            document.add_picture(filename, width=Inches(1))
            time.sleep(self.normalWaitingSecond)
        filename = tempfile.mktemp(suffix='.docx',prefix=title + '_')
        document.save(filename)

        # 发送邮件
        send_mail(settings.MAIL_LIST, title, u'见附件', [filename])
예제 #6
0
    def OnButton4Button(self, event):
        path = os.getcwd()
        vs.tr1300.SCPI.MMEMory.STORe.IMAGe = path + '\\temp.png'
        document = Document()
        document.add_heading('TEST REPORT',0)
        
        document.add_heading( u'品名' , level=1)
        document.add_paragraph(self.textCtrl1.Value, style='IntenseQuote')
        
        document.add_heading(u'型號', level=1)
        document.add_paragraph( self.textCtrl2.Value, style='IntenseQuote')
        
        


        document.add_picture(path + '\\temp.png', width=Inches(6))
        
        a = time.localtime()

        s = '%04d/%02d/%02d %02d:%02d:%02d' % (a[0],a[1],a[2],a[3],a[4],a[5])
        
        document.add_paragraph(s)
        t = path + '\\%04d%02d%02d_%02d%02d%02d.docx' % (a[0],a[1],a[2],a[3],a[4],a[5])        
        
        
        document.add_paragraph('Test by ' + self.choice1.GetString(self.choice1.GetSelection()))        
        document.save(t)    
        vs.tm += 1
        if vs.tm == 10:
            wx.MessageBox('The Demo program only can run 10 times.','Up to limit!', style = wx.CENTER | wx.ICON_WARNING | wx.OK)
            self.Close()
            self.Destroy()    
        event.Skip()
예제 #7
0
 def WriteTiezi(self):
     if len(self.pages)==0:
         print 'Error!'
     document = Document()
     # style = document.StyleSheet
     # style.Fonts.append(Font("\\'cb\\'ce\\'cc\\'e5", 'modern', 134, 30))
     # section = Section()
     # document.Sections.append(section)
     # tps = TextPS(font=getattr(style.Fonts, "\\'cb\\'ce\\'cc\\'e5"))
     for i in range(self.page_num):
             now_page = self.pages[i]
             for a in now_page:
                 for b in a:
                     document.add_paragraph(b.decode())
                 if len(a)>1:
                     # pic_num = len(self.img[a[0]])
                     if self.img.has_key(a[0]):
                         for k in self.img[a[0].decode()]:
                             pic_name = self.getImg(k)
                             document.add_picture(self.dirname + '/' + pic_name)
                 document.add_paragraph('---------------------------------')
     name = self.url.strip().split('/')
     name = name[-2] + name[-1]
     document.save(self.dirname + '/' + name + '.docx')
     print "Success to dump into " + name + '.docx'
예제 #8
0
def generate_docx(dictIn):
    """Takes either a list for unformatted text, or a dict with formatting options"""
    try:
        docStruct = dictIn["document"]
    except KeyError:
        docStruct = list(dictIn)
    documentReal = Document()

    # Try and build the document from a dict
    try:
        previousPara = False
        for key, value in docStruct.items():
            if value == "paragraph":
                if not previousPara:
                    paragraph = documentReal.add_paragraph("")
                paragraph.add_run(key)
                previousPara = True
            elif value == "title":
                previousPara = False
                documentReal.add_heading(key, level=0)
            elif value == "subtitle":
                previousPara = False
                documentReal.add_heading(key, level=1)
            elif value == "tagline":
                previousPara = False
                documentReal.add_heading(key, level=2)
            elif value == "bold":
                if not previousPara:
                    paragraph = documentReal.add_paragraph("")
                paragraph.add_run(key).bold = True
            elif value == "italic":
                if not previousPara:
                    paragraph = documentReal.add_paragraph("")
                paragraph.add_run(key).italic = True
            elif value == "bulletpoint":
                paragraph = documentReal.add_paragraph("")
                prun = paragraph.add_run("* " + key)
            elif value == "image":
                documentReal.add_picture(key, width=Inches(1.0))
            elif value == "paragraph":
                if not previousPara:
                    documentReal.add_paragraph("")
                paragraph.add_run(key)

    # If not a dict, process it as a list
    except AttributeError:
        for item in docStruct:
            documentReal.add_paragraph(item)
    # Save the file from the dict value
    try:
        documentReal.save(dictIn["outFile"])
    except KeyError:
        # Or save into the current working directory.
        folder = os.getcwd()
        if "\\" in folder:
            folder = folder.replace("\\", "/")
        documentReal.save(folder + "/save.docx")
예제 #9
0
파일: prograph.py 프로젝트: lucawen/Clima
def processa(_col_pontos, _col_campanha, _col_parametro,  _idleg, _idclasse):

    document = Document('/home/wbeirigo/Clima/weather/proj/matriz.docx')

    URL_PHANTOM = 'http://10.3.0.29:3003'
    headers ={ 'Content-Type': 'application/json', '-X POST':'' }
    indice = 0


    section = document.add_section()
    section.orientation = WD_ORIENT.LANDSCAPE
    indice += 1
    document.add_paragraph('  ', style='Normal')
    document.add_paragraph('  ', style='Normal')
    document.add_heading(u'Quadro 6.{0} - - Resultados do monitoramento da qualidade da água'.format(indice, ''), level=2)
    #geraTabela(document, _col_pontos, _col_campanha, _idleg, _idclasse)
    document.add_paragraph('  ', style='Normal')
    section = document.add_section()
    section.orientation = WD_ORIENT.PORTRAIT
    for parametro  in _col_parametro:

        """ Não processa parametros Data e Profundidade"""
        if parametro in (798,840):
            continue

        saida = geraGraphico(_col_pontos, _col_campanha, parametro, _idleg, _idclasse)
        if not saida:
            continue
        r = requests.post(URL_PHANTOM, data=saida, headers=headers)
        png_recovered = base64.decodestring(r.content)
        path = "/tmp/{0}.png".format(int(time.time()*1000))
        f = open(path, "w")
        f.write(png_recovered)
        f.close()

        indice += 1
        obj_param = Param.objects.get(pk=parametro)
        nome = obj_param.nome
        texto = obj_param.texto
        document.add_heading(u'6.{0} - {1}'.format(indice, nome), level=3)
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph(texto, style='Normal')
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph('  ', style='Normal')
        document.add_paragraph(u'Figura 6.{0} -Resultados obtidos para o parâmetro {1}'.format(indice, nome), style='f')
        document.add_picture(path, width=Inches(5.2))
        document.add_paragraph('  ', style='Normal')
        last_paragraph = document.paragraphs[-1]
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        document.add_page_break()
        os.remove(path)
    caminho = '/media/projeto_cemig/01_SOFTWARE/rel/'
    path = caminho + "{0}.docx".format(int(time.time()*1000))
    document.save(path)
    return path
예제 #10
0
def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    # 创建文档对象
    document = Document()
    
    # 设置文档标题,中文要用unicode字符串
    document.add_heading(u'我的一个新文档',0)
    
    # 往文档中添加段落
    p = document.add_paragraph('This is a paragraph having some ')
    p.add_run('bold ').bold = True
    p.add_run('and some ')
    p.add_run('italic.').italic = True
    
    # 添加一级标题
    document.add_heading(u'一级标题, level = 1',level = 1)
    document.add_paragraph('Intense quote',style = 'IntenseQuote')
    
    # 添加无序列表
    document.add_paragraph('first item in unordered list',style = 'ListBullet')
    
    # 添加有序列表
    document.add_paragraph('first item in ordered list',style = 'ListNumber')
    document.add_paragraph('second item in ordered list',style = 'ListNumber')
    document.add_paragraph('third item in ordered list',style = 'ListNumber')
    
    # 添加图片,并指定宽度
    document.add_picture('e:/docs/pic.png',width = Inches(1.25))
    
    # 添加表格: 1行3列
    table = document.add_table(rows = 1,cols = 3)
    # 获取第一行的单元格列表对象
    hdr_cells = table.rows[0].cells
    # 为每一个单元格赋值
    # 注:值都要为字符串类型
    hdr_cells[0].text = 'Name'
    hdr_cells[1].text = 'Age'
    hdr_cells[2].text = 'Tel'
    # 为表格添加一行
    new_cells = table.add_row().cells
    new_cells[0].text = 'Tom'
    new_cells[1].text = '19'
    new_cells[2].text = '12345678'
    
    # 添加分页符
    document.add_page_break()
    
    # 往新的一页中添加段落
    p = document.add_paragraph('This is a paragraph in new page.')
    
    # 保存文档
    document.save('e:/docs/demo1.docx')
예제 #11
0
def write_test_result_report_word(result_report):
    image_path = sys_tools.base_path + '\\auto_results\\screenshots\\' + result_report.screen_shot
    word_result_path = sys_tools.base_path + '\\auto_results\\test_results\\' + settings.test_result_file_name_word
    # image_path = '../auto_results/screenshots/' + result_report.screen_shot
    # word_result_path = '../auto_results/test_results/' + settings.test_result_file_name_word

    if os.path.exists(word_result_path):
        document = Document(word_result_path)
    else:
        document = Document()
    document.add_heading(result_report.report_name + ': ' + result_report.report_test_result.__str__() + '-' + result_report.browser.__str__(), level=1)
    document.add_paragraph(text='Test Result: ' + result_report.msg)
    document.add_picture(image_path, width=Inches(4.5))
    document.save(word_result_path)
예제 #12
0
def jpg2docx(doc_name, img, w):
    document = Document()
    sections = document.sections
    section = sections[0]

    section.page_width = Mm(80)
    section.page_height = Mm(297)
    section.top_margin = Mm(0)
    section.bottom_margin = Mm(0)
    section.left_margin = Mm(0)
    section.right_margin = Mm(0)

    document.add_picture(img, width=Mm(w))

    document.save(doc_name)
def initWord():
	document = Document()

	document.add_heading(u'微博搜索相关内容', 0)

	p = document.add_paragraph(u'详细内容,模板待修改')
	# p.add_run('bold').bold = True
	# p.add_run(' and some ')
	# p.add_run('italic.').italic = True

	document.add_heading(u'内容', level=1)
	#document.add_paragraph('Intense quote', style='IntenseQuote')




	import xlrd,os
	file = xlrd.open_workbook('./crawl_output_YS.xls')
	sheet= file.sheets()[0]
	nrows=sheet.nrows
	ncols = sheet.ncols
	
	for rownum in range(1,sheet.nrows):

		document.add_paragraph(sheet.cell(rownum,4).value, style='ListBullet')
		document.add_paragraph('     ')
		imgUrl.append(sheet.cell(rownum,5).value)
		path = 'img/'+str(rownum)+'.jpg'
		if os.path.exists(path):
			document.add_picture(path)
	

	#document.add_picture('monty-truth.png', width=Inches(1.25))

	
	# for item in recordset:
	#     row_cells = table.add_row().cells
	#     row_cells[0].text = str(item.qty)
	#     row_cells[1].text = str(item.id)
	#     row_cells[2].text = item.desc

	document.add_page_break()

	document.save('demo.docx')
예제 #14
0
파일: hawkDOCX.py 프로젝트: ddfelts/hawk2.0
class hawkDOCX():

    def __init__(self,name,template,hawk):
        self.doc = Document(template)
        self.secs = self.doc.sections
        self.name = name
        self.hlib = hawklib(hawk)
        self.cur = None

    def addPara(self,data):
        self.cur = self.doc.add_paragraph(data)

    def addHead(self,data):
        self.doc.add_heading(data,level=1)

    def addPageBreak(self):
        self.doc.add_page_break()

    def addImage(self,image,w=None):
        if w == None:
            self.doc.add_picture(image)
        else:
            self.doc.add_picture(image,width=Inches(w))

    def addTable(self,data,nkeys=None):
        if not nkeys:
            keys = self.hlib.getKeys(data)
        else:
            keys = nkeys
        table = self.doc.add_table(rows=1,cols=len(keys))
        row = table.rows[0]
        for i in range(len(keys)):
            row.cells[i].text = str(keys[i])
        for x in data:
            nrow = table.add_row().cells
            for b in range(len(keys)):
                if keys[b] not in x:
                    outb = None
                else:
                    outb = x[keys[b]]
                nrow[b].text = str(outb)

    def saveDoc(self):
        self.doc.save(self.name)
예제 #15
0
def main():
    start = str(raw_input("start from: "))
    end = str(raw_input("end to:"))
    # base_url = "http://www.tax.sh.gov.cn/wsbs/WSBSptFpCx_loginsNewl.jsp"
    base_url = "https://www.tax.sh.gov.cn/xbwz/wzcx/WSBSptFpCx_loginsNewl.jsp"
    browser = webdriver.Chrome()
    browser.maximize_window()
    browser.get(base_url)
    # browser.refresh()
    try:
        # 下三行把验证码提取出来可以做响应处理,验证码识别
        # cookies = browser.get_cookie("JSESSIONID")
        # print cookies
        # captcha = get_captcha(cookies)
        captcha = raw_input("input yzm: ")
        browser.find_element_by_id("invoiceNo").send_keys(INVOICENO)
        browser.find_element_by_id("fphm").send_keys(start)
        browser.find_element_by_id("revenueRegisterId").send_keys(
            REVENUEREGISTERID)
        browser.find_element_by_id("yzm").send_keys(captcha)
        browser.find_element_by_name("confirm").click()

        document = Document()

        # import pdb;pdb.set_trace()
        base_string = start
        count = 0
        for i in range(int(start), int(end) + 1):
            edit_to_string = "0" * (8 - len(str(i))) + str(i) if len(
                str(i)) <= 7 else str(i)
            edit_page(browser, base_string, edit_to_string)
            take_screenshot(browser, edit_to_string + '.png')
            document.add_picture(edit_to_string + '.png', width=Inches(4.25))
            os.remove(edit_to_string + '.png')
            base_string = edit_to_string
            count += 1
            print count, "/", int(end) + 1 - int(start)

        docName = 'taxVerify-' + datetime.datetime.now().strftime(
            '%Y-%m-%d-%H-%M-%S') + '.docx'
        document.save(docName)

    except Exception, e:
        print "Error!", e
예제 #16
0
    def __str__(self):
        self.publish()
        doc = Document(self.path)
        for school in self.result:
            school_name = list(school.keys())[0]
            school_info = school[school_name]

            page_title = doc.add_paragraph()
            page_title.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
            page_title.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            title_run = page_title.add_run(school_name)
            title_run.font.color.rgb = RGBColor(54, 95, 145)
            title_run.font.size = Pt(32)
            title_run.add_break(WD_BREAK.TEXT_WRAPPING)

            for header, info in school_info.items():
                para_header = doc.add_paragraph()
                para_header.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
                header_run = para_header.add_run(header)
                header_run.font.size = Pt(28)
                header_run.underline = True
                header_run.add_break()

                for sub_header, sub_info in info.items():
                    para_sub_header = doc.add_paragraph()
                    para_sub_header.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
                    sub_header_run = para_sub_header.add_run(sub_header)
                    sub_header_run.bold = True
                    sub_header_run.font.size = Pt(23)

                    if isinstance(sub_info, str):
                        para_sub_info = doc.add_paragraph()
                        para_sub_info.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
                        sub_info_run = para_sub_info.add_run(f'\t{sub_info} ')
                        sub_info_run.italic = True
                        sub_info_run.font.size = Pt(22)
                        sub_info_run.add_break(WD_BREAK.LINE_CLEAR_ALL)
                    else:
                        doc.add_picture(sub_info, width=Inches(5))
                        doc.add_paragraph('\n')
                doc.add_paragraph('\n')
            doc.add_page_break()
        doc.save(self.path)
        return 'Succeed'
예제 #17
0
def create_document(random_article, topic):
    # creation of .docx
    print('creating and saving docx file')
    document = Document()
    document.add_heading(topic.upper(), 0)

    m = len(os.listdir('./photos/'))
    n = sum([len(random_article[key]) for key in random_article.keys()])
    if n > m:
        r = m/(n * 5)
    else:
        r = n/(m * 5)
    image_chance = 1

    for key in random_article.keys():
        split_index = random.randint(10,20)
        part = ''
        for index, sentence in enumerate(random_article[key]):
            part += sentence + '. '
            if index == split_index:
                document.add_heading(get_header(part, random.randint(1,3)), 2)
                paragraph = document.add_paragraph()
                paragraph.add_run(part)
                split_index += random.randint(10,15)
                part = ''
            image_chance -=  r
            if uniform() > image_chance:
                try:
                    filename = os.listdir('./photos/')[0]
                    try:
                        document.add_picture('./photos/' + filename)
                    except:
                        pass
                    image_chance = 1
                    os.remove('./photos/' + filename)
                except Exception as ex:
                    continue

                
        document.add_heading(get_header(part, random.randint(2,4)), 2)
        paragraph = document.add_paragraph()
        paragraph.add_run(part)
    document.save('report.docx')
    shutil.rmtree('./photos')
예제 #18
0
class CreateDoc(object):
    def __init__(self):
        self.__document = Document()
        self.head = self.__document.add_heading('ATP运行结果分析报告', 0)
        self.para_file = self.__document.add_paragraph(u'运行的ATP文件:')
        self.para_times = self.__document.add_paragraph(u'总仿真次数:')
        self.para_dataTable = self.__document.add_paragraph(u'运行所得数据图表:')

    def __addtoPara(self, paraNum, content):
        p = self.__document.paragraphs[paraNum]
        p.add_run('  ' + content)

    def addFilePara(self, content):
        self.__addtoPara(1, content)

    def addTimsPara(self, content):
        self.__addtoPara(2, content)

    def addTablePara(self, txtPath, mma):
        self.__document.add_paragraph(' ' + mma + '_table:')
        txtFileName = txtPath + '_%s.txt' % (mma)
        file = open(txtFileName)

        data = []
        for i in file.readlines():
            data.append(list(map(str.strip, i.split())))
        file.close()

        table = self.__document.add_table(len(data), len(data[0]))
        print(len(data), len(data[0]))
        i, j = 0, 0
        for row in table.rows:
            j = 0
            for cell in row.cells:
                cell.text = data[i][j]
                j += 1
            i += 1

    def addPicture(self, picturePath):
        pictureFileName = picturePath + '_pl4.png'
        self.__document.add_picture(pictureFileName, width=Inches(3))

    def saveDoc(self, filepath):
        self.__document.save(filepath + '.docx')
예제 #19
0
파일: chart.py 프로젝트: Nenu1985/stend
    def plot_to_word(self):
        FILE_EXISTS = False
        # create an exporter instance, as an argument give it
        # the item you wish to export
        exporter = PGQ_image_exporter.PQG_ImageExporter(self.chart)

        # set export parameters if needed
        # exporter.parameters()['width'] = 600

        # save to file
        exporter.export('fileName.jpg')

        word_file_name = self.lineEdit_word_file_path.text()
        try:
            document = Document(word_file_name)
            FILE_EXISTS = True
        except PackageNotFoundError as e:
            try:
                document = Document()
            except Exception as e:
                print('Error while creating word template: {}'.format(e))
        except Exception as e:
            print('Error while saving to word {}'.format(e))
            return

        document.add_paragraph('График добавлен. {}'.format(
            datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        document.add_picture('fileName.jpg')

        for file_name in self.files_names:
            document.add_paragraph(file_name)
        document.add_page_break()

        try:
            document.save(word_file_name)
        except PackageNotFoundError as e:
            print('Package not found exception while saving to word')
            return
        except Exception as e:
            print('Error while saving to word {}'.format(e))
            return

        Chart.display_ok_message('Word saved!')
예제 #20
0
def generate():
    document = Document()

    document.add_heading('Blame Report', 0)

    p = document.add_paragraph(
        "Ok ok, I'll change the name. This is an example paragraph"
        " with any information you want to add statically to the report."
        " I can format elements in  ")
    p.add_run('bold').bold = True
    p.add_run(' and ')
    p.add_run('italic.').italic = True

    document.add_heading('Report', level=1)
    document.add_paragraph('Problem type being reported',
                           style='Intense Quote')

    document.add_paragraph('First issue being reported', style='List Bullet')
    document.add_paragraph('Second issue being reported', style='List Bullet')
    document.add_paragraph('Proof pictures can be added here',
                           style='List Number')

    document.add_picture('/home/tesla/Desktop/code/Service/Reports/3.PNG',
                         width=Inches(3.75))

    records = (('John Doof', '22345678', 'Mill uncleaned'),
               ('Jane Dirty', '21354126', 'unreported tool breakage'),
               ('Innocent Accused', '20967347', 'Unmatched signin'))

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Name'
    hdr_cells[1].text = 'Student Id'
    hdr_cells[2].text = 'Reason for report'
    for qty, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = str(qty)
        row_cells[1].text = id
        row_cells[2].text = desc

    document.add_page_break()

    document.save(f"Service/Reports/{date.today()}_report.docx")
예제 #21
0
    def criarDocumentoDeEvidencia(self, diretorioEvidencia,id ,nomeEvidencia):
        try:
            document = Document()

            document.add_heading('Evidências: Calculadora Android', 0)
            p = document.add_paragraph(nomeEvidencia)

            document.add_paragraph(id+'_Tela01')
            document.add_picture(diretorioEvidencia + '/Ev1.png', width=Inches(4.14))
            #document.add_page_break()

            document.add_paragraph(id+'_Tela02')
            document.add_picture(diretorioEvidencia + '/Ev2.png', width=Inches(4.14))
            #document.add_page_break()

            document.save(diretorioEvidencia + '/' + nomeEvidencia + '.docx')
            print("Documento com as evidencias gerada com sucesso!")
        except:
            print("Não foi possivel criar o documento com as evidencias!")
예제 #22
0
 def Total_file(self):
     try:
         document = Document()
         document.add_picture('LOGO.png')
         document.add_heading('Here are some awesome Pets to find')
         p = document.add_paragraph(
             'Below is a table containing All animals currently up for adoption!'
         )
         with sqlite3.connect('Data.db') as db:
             data = db.cursor()
             data.execute(
                 'select Animal_ID, Animal_Name, Animal_Type, Animal_Gender, Animal_breed, Animal_colour, Address from "Animal Data"'
             )
         data = data.fetchall()
         table = document.add_table(rows=1, cols=11)
         style = document.styles['Normal']
         font = style.font
         font.name = 'Arial'
         font.size = Pt(6)
         hdr_cells = table.rows[0].cells
         hdr_cells[0].text = 'Animal ID'
         hdr_cells[1].text = 'Animal Name'
         hdr_cells[2].text = 'Animal Type'
         hdr_cells[3].text = 'Animal Gender'
         hdr_cells[4].text = 'Animal breed'
         hdr_cells[5].text = 'Animal colour'
         hdr_cells[6].text = 'address'
         for Animal_ID, Animal_Name, Animal_Type, Animal_Gender, Animal_breed, Animal_colour, Address in data:
             row_cells = table.add_row().cells
             row_cells[0].text = str(Animal_ID)
             row_cells[1].text = str(Animal_Name)
             row_cells[2].text = str(Animal_Type)
             row_cells[3].text = str(Animal_Gender)
             row_cells[4].text = str(Animal_breed)
             row_cells[5].text = str(Animal_colour)
             row_cells[6].text = str(Address)
         document.add_page_break()
         document.save('Animal Place Pets.docx')
         tk.messagebox.showinfo(
             "success", "success you now have all of our pets information ")
     except:
         tk.messagebox.showinfo("ERROR",
                                "There has unfortunately been an Error")
예제 #23
0
def doc_template():
    doc = Document()
    doc.add_heading('Il mio primo report ', 0)
    folder = "static/report/"

    todisplaylist = [
        "andamento_nazionale.png", "variazione_totale_positivi.png"
    ]
    for name in todisplaylist:
        path = os.path.join(folder, name)
        doc.add_picture(path, width=Inches(6))

    file_stream = io.BytesIO()
    doc.save(file_stream)
    file_stream.seek(0)
    return send_file(file_stream,
                     as_attachment=True,
                     attachment_filename='report.docx',
                     cache_timeout=0)
예제 #24
0
    def gen_Dist(self,data,titlename,Var_lst):
        document = Document()

        document.add_heading('Distribution_{}_{} instances'.format(titlename,len(data)), 0)

        for var in Var_lst:
            plt.clf()
            sns.distplot(data[var].dropna())
            plt.title('Distribution(dropna={}) {}'.format(data[var].isnull().sum(),var), fontsize=12)
            plt.ylabel('frequncy')
            plt.tight_layout()
            fold_path_img = os.path.join(self.datasavedir,'img','{}'.format(titlename))
            save_path_img = self.check_savepath(foldpath=fold_path_img,filename='{}_{}_dist.jpg'.format(titlename,var))
            plt.savefig(save_path_img)
            document.add_picture(save_path_img,width=Inches(4.5))

        fold_path_doc = os.path.join(self.datasavedir,'doc','{}'.format(titlename))
        save_path_doc = self.check_savepath(foldpath=fold_path_doc,filename='Dist_{}.docx'.format(titlename))
        document.save(save_path_doc)
예제 #25
0
def process_string_to_doc(string, filename):
    document = Document()
    array = string.split('||')[1:]
    n = len(array)
    i = 0
    print array
    while i < n:
        if array[i] == 'small':
            document.add_heading(array[i + 1], level=1)
        elif array[i] == 'medium':
            document.add_heading(array[i + 1], level=2)
        elif array[i] == 'large':
            document.add_heading(array[i + 1], level=3)
        elif array[i] == 'img':
            document.add_picture(array[i + 1])
        else:
            document.add_paragraph(array[i + 1])
        i += 2
        document.save(filename)
예제 #26
0
파일: report.py 프로젝트: yuanhuiru/xnr1
 def save_word(self):
     results = self.userList()
     if results:
         self.screen_shot(results)
         document = Document()
         for result in results:
             str = json.dumps(
                 result, ensure_ascii=False).replace('{', '').replace(
                     '}', '').replace('event_name', u'上报名称').replace(
                         'report_time',
                         u'上报时间').replace('report_type', u'上报类型').replace(
                             'xnr_user_no',
                             u'虚拟人').replace('text', u'文本内容').replace(
                                 'user',
                                 u'发博用户').replace('timestamp', u'发博时间')
             document.add_paragraph(str)
             document.add_picture(result['mid'] + '.png')
         document.add_page_break()
         document.save(self.id + '.docx')
예제 #27
0
def PrintMethod(printStatus,fig):
                        
        if printStatus == 'yes':
            
            '''File name extension must be docx'''
            
            filename = input("Name your file, ex 'Plot.docx'")
            name,ext = filename.split('.')
            fig.savefig(name+'.png')
            document = Document()
            document.add_heading('Plot',0)
            document.add_picture(name+'.png',width=Inches(7))
            '''file must be saved to Documents in order to print, change user as required'''
            document.save('C:/Users/dylan.hematilake/Documents/'+filename)
            printWordDocument(filename)
        word.Quit()
          
        if printStatus == 'no':
                plt.show() 
예제 #28
0
class writeDoc:
    def __init__(self):
        self.document = Document()

    def addHeading(self, heading):
        self.document.add_heading(heading, 0)

    def addParagraph(self, paragraph):
        p = self.document.add_paragraph(paragraph)

    def addImage(self, img_path):
        self.document.add_picture(img_path, width=Inches(1.25))

    def addPage_break(self):
        self.document.add_page_break()
        pass

    def saveDoc(self, name):
        self.document.save(name)
예제 #29
0
def get_docx(request):
    document = Document()
    start_date = datetime.strptime(str(request.GET.get("start")), "%Y-%m-%d")
    end_date = datetime.strptime(str(request.GET.get("end")), "%Y-%m-%d") + timedelta(days=1)

    all_articles = Article.objects.all().filter(created_at__range=(start_date, end_date))
    articles = dict()
    for theme_choice in THEME_CHOICES:
        articles[theme_choice[1]] = all_articles.all().filter(theme=theme_choice[0])

    document.add_paragraph('Table of Contents', style='TOC Heading')
    paragraph = document.add_paragraph()
    add_toc(paragraph)

    document.add_page_break()

    for theme in articles.keys():
        if len(articles[theme]) > 0:
            document.add_heading(theme, level=1)
            for article in articles[theme]:
                document.add_heading(article.title, level=2)

                p = document.add_paragraph()
                add_head(p, article)

                if article.image_url:
                    image_response = requests.get(article.image_url)
                    binary_img = BytesIO(image_response.content)
                    document.add_picture(binary_img, width=Inches(5.5))

                document.add_paragraph(article.abstract)

                if article.keywords:
                    document.add_paragraph(article.keywords)

                document.add_page_break()

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=download.docx'
    document.save(response)

    return response
예제 #30
0
def ParagrapgStyle1(ti, txt):
    #修改正文的中文字体类型,示例代码:(全局设置)
    document = Document()
    document.styles['Normal'].font.name = u'宋体'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

    document.add_heading('')
    p = document.add_paragraph('', style='Heading 2')

    #添加了一个段落,不是添加标题,只是在段落上添加文字
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    title = p.add_run(ti)
    title.font.name = u'宋体'
    title.bold = True
    title.font.size = Pt(15)
    title._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

    p2 = document.add_paragraph('')
    #整个段落使用首行缩进0.25厘米
    p2.paragraph_format.first_line_indent = Inches(0.25)
    #txt = '正月里采花无哟花采,二月间采花花哟正开,二月间采花花哟正开。三月里桃花红哟似海,四月间葡萄架哟上开,四月间葡萄架哟上开。'
    text = p2.add_run(txt)
    font = text.font
    font.name = 'Calibri'
    font.size = Pt(10.5)

    document.add_picture('1.png', width=Inches(6.3))

    document.add_heading('')

    ti = '第二部分'
    p3 = document.add_paragraph('', style='Heading 2')

    # 添加了一个段落,不是添加标题,只是在段落上添加文字
    p3.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    title = p3.add_run(ti)
    title.font.name = u'宋体'
    title.bold = True
    title.font.size = Pt(15)
    title._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

    document.save('段落.docx')
예제 #31
0
def handle_upload_fragment(driveAPI, fileBytes, driveConnect, dirId, docNum,
                           failedFragmentsSet, debug_log):
    # Add a "spacer byte" at the end to indciate end of data and start of padding.
    fileBytes += bytes([255])

    # Generate a new Word document.
    doc = Document()

    # Pad the fragment with enough null bytes to reach the requirements for the image dimensions.
    fileBytes += bytes(10224000 - len(fileBytes))

    # Calculate CRC32 hash for fileBytes
    hash = hex(crc32(fileBytes))

    # Generate and save a temporary PNG in memory.
    img = Image.frombytes('RGB', (2000, 1704), fileBytes)
    mem_img = BytesIO()
    img.save(mem_img, 'PNG')

    # Add temporary PNG to the Word document.
    doc.add_picture(mem_img)

    # Save the generated Word document.
    mem_doc = BytesIO()
    doc.save(mem_doc)

    # Upload Word document to Google Drive
    while True:
        try:
            driveAPI.store_doc(driveConnect, dirId,
                               str(docNum) + ".docx", hash, mem_doc)
        except Exception as e:
            # If a fragment upload failure occurs, log the incident, add docNum to failedFragmentsSet,
            # and try again.
            debug_log.write("----------------------------------------\n")
            debug_log.write("Fragment upload failure. Fragment number is " +
                            str(docNum) + ".\n")
            debug_log.write("Error:\n")
            debug_log.write(str(e) + "\n")
            failedFragmentsSet.add(docNum)
            continue
        break
예제 #32
0
def MakeReport():
    from SaraModules import SaraSpeak
    from SaraModules import SaraListen
    SaraSpeak.SpeakChinese('請問你要做什麼主題的報告')
    time.sleep(2)
    temp=SaraListen.Listen()
    if temp:
        Doctitle=temp
    else:
        SaraSpeak.SpeakChinese('不好意思我不太了解 你可以輸入給我嗎')
        Doctitle=input('請問你要做什麼報告?')
    downloadImage(Doctitle)
    path1=os.path.abspath('..')
    imagePath=path1+"/"+Doctitle+"/"+getImagefileName(Doctitle)
    print("相片路徑"+imagePath)
    document = Document()
    document.add_heading(Doctitle, 0)
    res=requests.get('https://zh.wikipedia.org/wiki/{}'.format(Doctitle))
    soup=BeautifulSoup(res.text,'lxml')
    result=soup.find_all('p')
    par1=str(result[0].text)
    par1 = re.sub(u"\\(.*?\\)|\\{.*?}|\\[.*?]", "", par1)
    document.add_paragraph(par1)
    document.add_picture(imagePath, width=Inches(6), height=Inches(4))
    result2=soup.find_all('h3')
    for r in result2:
        result=str(r.text)
        result = re.sub(u"\\(.*?\\)|\\{.*?}|\\[.*?]", "", result)
        print("標題 :"+result)
        para = r.find_next_sibling('p')
        if para==None:
            docpath=os.path.abspath('..')
            document.save(docpath+"/"+Doctitle+".doc")
            return
        else:       
            para=str(para.text)
            if len(para)<10:
                continue
            para=re.sub(u"\\(.*?\\)|\\{.*?}|\\[.*?]", "", para)
            document.add_heading(result, 0)
            document.add_paragraph(para)
            print("內容 : "+para)
예제 #33
0
    def test_python_docx(self):
        document = Document()

        document.add_heading('Document Title', 0)

        p = document.add_paragraph('A plain paragraph having some ')
        p.add_run('bold').bold = True
        p.add_run(' and some ')
        p.add_run('italic.').italic = True

        document.add_heading('Heading, level 1', level=1)
        document.add_paragraph('Intense quote', style='Intense Quote')

        document.add_paragraph(
            'first item in unordered list', style='List Bullet'
        )
        document.add_paragraph(
            'first item in ordered list', style='List Number'
        )

        document.add_picture('pictures/DRG Clinical Profile.png', width=Inches(1.25))

        records = (
            (3, '101', 'Spam'),
            (7, '422', 'Eggs'),
            (4, '631', 'Spam, spam, eggs, and spam')
        )

        table = document.add_table(rows=1, cols=3)
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Qty'
        hdr_cells[1].text = 'Id'
        hdr_cells[2].text = 'Desc'
        for qty, id, desc in records:
            row_cells = table.add_row().cells
            row_cells[0].text = str(qty)
            row_cells[1].text = id
            row_cells[2].text = desc

        document.add_page_break()

        document.save('demo.docx')
def to_wps():
    strings = ["每张图片的标题"]
    images = ['每张图片的名称']
    # 保存在本地的图片
    doc = Document()
    p = doc.add_heading(level=0)
    # p = doc.add_paragraph(style='ListBullet')
    run = p.add_run('网络运营日报')
    # doc.add_paragraph(style='ListBullet')
    # run.bold = True#加粗
    run.font.name = u'Cambria'  #设置字体名称
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'Cambria')
    run.font.color.rgb = RGBColor(0, 0, 0)  #设置字体颜色
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    doc.add_paragraph('1 关键链路使用情况明细(一周)')
    data = xlrd.open_workbook(
        r"/usr/local/python_on/Daily_automation_linux/xunjian/巡检报告.xlsx")
    # 获取sheet,通过序号
    table = data.sheet_by_index(0)
    excel = doc.add_table(rows=8, cols=5, style="Table Grid")

    for i in range(0, 8):
        excel.cell(i, 0).text = table.cell(i, 0).value
        excel.cell(i, 1).text = table.cell(i, 1).value
        excel.cell(i, 2).text = table.cell(i, 2).value
        excel.cell(i, 3).text = table.cell(i, 3).value
        excel.cell(i, 4).text = table.cell(i, 4).value

    doc.add_paragraph()  #输出一个空格

    for (string, image) in zip(strings, images):
        doc.add_paragraph(string)  # 添加文字
        try:
            doc.add_picture(image, width=Inches(6))  # 添加图, 设置宽度
        except Exception:
            jpg_ima = Image.open(image)  # 打开图片
            jpg_ima.save('0.jpg')  # 保存新的图片
            doc.add_picture(image, width=Inches(6))  # 添加图, 设置宽度
    # doc.save('D:\python_on\Daily_automation\Daily word\网络运营日报.doc')  # 保存路径
    # doc.save('D:\python_on\Daily_automation\Daily word\%d.网络运营日报.doc' % float(time.time() * 10000000))  # 保存路径
    doc.save(
        '/usr/local/python_on/Daily_automation_linux/Daily_word/网络运营日报.doc')
예제 #35
0
class EvidenceGenerator:
    """Essa classe cria do documento final com as evidências do teste
    """
    def __init__(self, project, exec_time, final_result):
        self.document = Document()
        self.FillHeader(project, exec_time, final_result)

    def FillHeader(self, project, exec_time, final_result):
        """Preenche cabeçalho do report

        @param project: nome do projeto
        @param exec_time: tempo de execução da suíte
        @final_result: resultado final da execução dos testes (if failed>0 then Failed else Passed)
        """
        self.document.add_heading('Evidence document', 0)
        records = ((project, exec_time, final_result), )
        table = self.document.add_table(rows=1, cols=3)
        table.style = 'Table Grid'
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = 'Project'
        hdr_cells[1].text = 'Execution time'
        hdr_cells[2].text = 'Final Result'
        for qty, _id, desc in records:
            row_cells = table.add_row().cells
            row_cells[0].text = str(qty)
            row_cells[1].text = _id
            row_cells[2].text = desc

    def AddEvidence(self, test_name, evidence_name, picture):
        """Adiciona evidência ao documento
        
            @param test_name: nome do teste daquela evidência
            @param evidence_name: nome do screenshot
            @param picture: path do screenshot
        """
        self.document.add_heading(test_name, level=1)
        self.document.add_paragraph(evidence_name, style='Intense Quote')
        self.document.add_picture(picture, width=Inches(6.25))
        self.document.add_page_break()

    def CreateDocument(self, doc_test):
        self.document.save(doc_test)
예제 #36
0
def make_new_file():
    document = Document()
    document.add_heading('试题导出', 0)  # 好像是标题一样的东西哦
    p = document.add_paragraph('这 是一个p')
    p.add_run('bold').bold = True  # 加粗
    p.add_run(' and some ')  # 正常文字
    p.add_run('italic.').italic = True  # 斜体

    document.add_heading('Heading, level 1', level=1)  # 一级标题样式
    document.add_paragraph('Intense quote', style='Intense Quote')  # 明显引用

    document.add_paragraph(
        'first item in unordered list', style='List Bullet'
    )  # 项目符号列表
    document.add_paragraph(
        'first item in ordered list', style='List Number'
    )  # 数字编号

    document.add_picture('achievement_gurenl.png', width=Inches(1.25))  # 插入图片!有用的功能!

    # ----------插入表格儿------------------------
    records = (
        (3, '101', 'Spam'),
        (7, '422', 'Eggs'),
        (4, '631', 'Spam, spam, eggs, and spam')
    )  # 插入表格儿

    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'
    for qty, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = str(qty)
        row_cells[1].text = id
        row_cells[2].text = desc
    # -------------------------------------------

    document.add_page_break()  # 加入分页符

    document.save('demo.docx')
예제 #37
0
class Write2docx(object):
    def __init__(self):
        self.document = Document()
        self.mongo_collection = pymongo.MongoClient()['sinanews']['info']
    def _download_img(self, url):
        imgdata = requests.get(url).content
        return imgdata

    def _getdata(self):
        title = self.mongo_collection.find()
        return title


    def write_img(self,url):
        imgdata = self._download_img(url)
        image_io = BytesIO()
        image_io.write(imgdata)
        image_io.seek(0)
        im = Image.open(image_io)
        self.document.add_picture(image_io,width=Inches(3))
예제 #38
0
def DOCX_Output(Object, Title, Plugin_Name, Domain, Link, Result_Type,
                Output_File, Task_ID, Directory):

    try:
        Use_DOCX = Load_Output(Object, "docx")

        if Use_DOCX:
            File_Dir = os.path.dirname(os.path.realpath('__file__'))
            Complete_File = f"{File_Dir}/static/protected/output/{Directory}/{Plugin_Name}-Output.docx"

            if os.path.exists(Complete_File):
                document = Document(Complete_File)

            else:
                from docx.shared import Inches
                from docx.enum.text import WD_ALIGN_PARAGRAPH
                document = Document()
                h1 = document.add_heading(
                    f'Scrummage Finding Report for {Plugin_Name} Plugin', 0)
                h1.alignment = WD_ALIGN_PARAGRAPH.CENTER
                image = document.add_picture(
                    f"{File_Dir}/static/images/search.png", width=Inches(2.00))
                last_paragraph = document.paragraphs[-1]
                last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                document.add_page_break()

            Document_Data = (('Plugin', Plugin_Name), ('Domain', Domain),
                             ('Link', Link), ('Created At', str(Date())),
                             ('Result Type', Result_Type), ('Output Files',
                                                            Output_File),
                             ('Associated Task ID', str(Task_ID)))

            table = document.add_table(rows=1, cols=2)
            hdr_cells = table.rows[0].cells
            hdr_cells[0].text = 'Title'
            hdr_cells[1].text = Title

            for name, data in Document_Data:
                row_cells = table.add_row().cells
                row_cells[0].text = name
                row_cells[1].text = data

            document.add_page_break()
            document.save(Complete_File)
            logging.info(
                f"{Date()} - Common Library - Exported to DOCX file located at {str(Complete_File)}."
            )
            return Complete_File

        else:
            return None

    except Exception as e:
        logging.warning(f"{Date()} - Common Library - {str(e)}.")
예제 #39
0
class Doc:
    def __init__(self, image, table, method_name):
        self.image_stream = image
        self.data = table
        self.method = method_name

    def save(self, name):
        self.name = name

        default_path = os.path.join(os.getenv("TEMP"), 'default.docx')
        QtCore.QFile.copy(':/help_docs/default.docx', default_path)

        self._save(default_path)
        try:
            os.remove(default_path)
        except:
            pass

    def _save(self, default_path):
        self.document = Document(default_path)

        self.document.add_heading(self.method, 0)
        self.document.add_heading('Рисунок', level=1)
        self.document.add_picture(self.image_stream, width=Inches(6))

        self.document.add_page_break()
        self.document.add_heading('Таблица', level=1)

        headers = list(self.data[0].keys())
        table = self.document.add_table(rows=len(self.data) + 1, cols=len(headers))
        table.style = 'Light Grid Accent 1'

        hdr_cells = table.rows[0].cells
        for i, head in enumerate(headers):
            hdr_cells[i].text = head

        for i, d in enumerate(self.data):
            for j, (_, value) in enumerate(d.items()):
                table.cell(i + 1, j).text = str(value)

        self.document.save(self.name)
예제 #40
0
def createDocForOneMetric(dir, label_mode):
    metrics = extraktLastDirFromPath(dir)
    document = Document()
    header = document.add_heading('Report: ', 1)

    listOfTrueLabels = []
    listOfPredictedLabels = []
    listOfK = []

    for r, d, f in os.walk(dir):
        header.add_run(metrics + ' mertics').bold = True
        for file in f:
            if isCorrectFileName(file):
                pathToFileWithClassificationData = os.path.abspath(dir)

                k = extraktNumberOfK(file)
                trueLabels, predictedLabels = extractClassificationCases(pathToFileWithClassificationData + "\\" + file)
                plot_confusion_matrix(trueLabels, predictedLabels, classes=unique_labels(trueLabels, predictedLabels),
                                      normalize=True,
                                      title='Normalized confusion matrix for ' + str(k) + ' k')
                memfile = StringIO()
                plt.savefig(memfile)
                document.add_paragraph('Confusion matrix for ' + str(k) + ' k.', style='List Number')
                document.add_picture(memfile, width=Inches(5))
                memfile.close()
                plt.close()

                listOfTrueLabels.append(trueLabels)
                listOfPredictedLabels.append(predictedLabels)
                listOfK.append(k)

    if label_mode == "single":
        plotClassificationQualityForSingleLabel(listOfTrueLabels, listOfPredictedLabels, listOfK)
    elif label_mode == "multi":
        plotClassificationQualityForMultiLabels(listOfTrueLabels, listOfPredictedLabels, listOfK)
    memfile = StringIO()
    plt.savefig(memfile)
    document.add_paragraph('Classification quality char for all k.', style='List Number')
    document.add_picture(memfile, width=Inches(6))
    memfile.close()
    document.save('report_' + metrics + '.docx')
예제 #41
0
def result(src_file):
    document = Document()
    document.add_heading(
        '                                                              Result')
    document.add_heading('  Grade:', level=2)
    paragraph = document.add_paragraph('            C')
    document.add_heading('Sentiment Analysis:')
    document.add_picture(src_file + '_sentiment.png')
    document.add_heading('Programming Languages:')
    f = open(src_file + "_pro_lang.txt", 'r')
    temp = f.read()
    f.close()
    l = temp.split("\n")
    del (l[-1])
    for x in l:
        paragraph = document.add_paragraph(x, style='ListBullet')
    document.add_page_break()
    document.add_heading('Spelling Mistakes:')
    document.add_heading(
        'Incorrect                                                 Correct')
    f = open(src_file + "_spell_ext.txt")
    temp = f.read()
    l = temp.split("\n")
    del (l[-1])
    table = document.add_table(rows=len(l), cols=2)
    i = int(0)
    for x in l:
        er = x.split(":")
        for j in range(0, 2):
            cell = table.cell(i, j)
            cell.text = er[j]
        i += 1
    document.add_heading('Subject Of Intrest:')
    f = open(src_file + "_sub.txt", "r")
    temp = f.read()
    l = temp.split("\n")
    del (l[-1])
    for x in l:
        paragraph = document.add_paragraph(x, style='ListBullet')
    document.save("E:/xampp/htdocs/Parser/Output/" + src_file + ".docx")
    '''
예제 #42
0
    def create(self, project):
        document = Document()
        obj_style = document.styles['Normal']
        obj_font = obj_style.font
        obj_font.size = Pt(12)
        obj_font.name = 'Tahoma'

        img_idx = 1
        for image in project.sorted_images:
            if len(image.caption
                   ) > 5:  #no caption if less than 5 characters in caption
                img_txt = str(img_idx) + ". " + image.caption
                p = document.add_paragraph(style='Normal', text=img_txt)
                p = document.paragraphs[-1]
                p.line_spacing = 1.0
                #p = document.add_paragraph(style ='ListBullet',text = img_txt)
                #p.num_id = img_idx
                #p.level = 0
                #p.line_spacing_rule = WD_LINE_SPACING.AT_LEAST
                p.line_spacing_rule = WD_LINE_SPACING.EXACTLY

                #p.line_spacing = 1.5

                img_full_url = os.path.join(
                    settings.MEDIA_ROOT,
                    image.image.url.split('/media/')[1])
                im = Image.open(img_full_url)
                (img_width, img_len) = im.size
                if img_width > img_len:  #wide picture
                    document.add_picture(img_full_url, height=Inches(3.25))
                else:
                    document.add_picture(img_full_url, width=Inches(2.44))

                p = document.paragraphs[-1]  # grab the last paragraph
                p.alignment = WD_ALIGN_PARAGRAPH.CENTER  # center image
                img_idx += 1
                if img_idx % 2:  #add two images and then page break
                    document.add_page_break()
            #else:
            #	document.add_paragraph(" ") #add line break
        return document
예제 #43
0
def parsePageAndGenDocFile(link):
    cotent = getPageContent(link, req_header)
    if cotent == "" :
        return
    soupContent = BeautifulSoup(cotent)
    title = ""
    if soupContent.find(attrs={"class" : "status-title"}) :
        title = soupContent.find(attrs={"class" : "status-title"}).contents[0]
    print title
    pageContent = soupContent.find(attrs={"class" : "detail"})
    comments = soupContent.findAll(text=lambda text:isinstance(text, Comment))
    [comment.extract() for comment in comments]
    
    scripts = soupContent.findAll("script")
    [script.extract() for script in scripts]
    
    brs = soupContent.findAll("br")
    [br.extract() for br in brs]
    
    document = Document()
    document.add_heading(title, 0)
    
    for line in pageContent.contents :
        try :
            if  line.find("img class=\"ke_img\"") != -1 :
                imagePath = line.get("src").encode("utf-8").replace("!custom.jpg", "")
    #             imagePath = imagePath.findAll("^http:.*jpg")
                print imagePath
                
                image_from_url = urllib2.urlopen(imagePath)
                io_url = StringIO.StringIO()
                io_url.write(image_from_url.read())
                io_url.seek(0)
                document.add_picture(io_url, width=Inches(4))
            else :   
                document.add_paragraph(line)
        except Exception,ex:
            print line
예제 #44
0
파일: docgen.py 프로젝트: fpt/webtoys
class DocWriter(BaseWriter):
    """Factory"""

    def __init__(self, fp):
        self.fp = fp
        self.document = Document()

    def add_heading(self, str, level=None):
        self.document.add_heading(str, level=level)

    def add_paragraph(self, str):
        self.document.add_paragraph(str)

    def add_image(self, img):
        img_bytes = BytesIO()
        img.save(img_bytes, format="png")
        img_bytes.seek(0)
        self.document.add_picture(img_bytes)

    def add_page_break(self):
        self.document.add_page_break()

    def close(self):
        self.document.save(self.fp)
예제 #45
0
            CR.add_paragraph(u'Autre antécédents familiaux: ' + str(df.Family_history_disorder_3[0]) + u" (degré de certitude: " + \
            str(df.Family_history_confidence_3[0]) + u"/3), chez un membre au " + str(df.Family_history_degree_3[0]) + u' degré coté ' +\
            str(df.Family_history_side_3[0]) + u'.')
        if pandas.isnull(df.Family_history_disorder_4[0]) == False:
            CR.add_paragraph(u'Autre antécédents familiaux: ' + str(df.Family_history_disorder_4[0]) + u" (degré de certitude: " + \
            str(df.Family_history_confidence_4[0]) + u"/3), chez un membre au " + str(df.Family_history_degree_4[0]) + u' degré coté ' +\
            str(df.Family_history_side_4[0]) + u'.')           
        
        
        CR.add_heading(u"Résultats de l'examen", level=1)
        db_origin = pandas.read_csv(os.getcwd().split('\\Files')[0] + '/Data/Database.csv',header = 0,engine='python',sep=';',decimal='.')
        
        CR.add_paragraph(u'Les analyses suivantes ont été effectuées en comparant le patient par rapport à une population aux caractéristiques suivantes: n = '\
        + str(len(db_origin.Age)) + '; Age moyen = ' + str("{0:.2f}".format(np.average(db.Age))) + '; ' + str("{0:.2f}".format(float(len(db_origin.Sex[db_origin.Sex == 'f']))/float(len(db.Sex))*100)) + ' % de femmes')
        

        CR.add_heading(u"Age", level=2) 
        CR.add_picture('./Files/Docs/Temporary/Age.png', width=Inches(5))      


        
        CR.add_heading(u"Personalité", level=2) 
        
        
        
        
        CR.save(os.getcwd().split('\\Files')[0] + '/Data/'+subject_code+'/'+subject_code+'_CR.docx')

finally:
    pygame.quit()
예제 #46
0
url = "http://freebuf.com/news/94263.html"
data = urllib.urlopen(url)

document = Document()

soup = BeautifulSoup(data)
article = soup.find(name = "div",attrs={'id':'contenttxt'}).children
for e in article:
    try:
        if e.img:
            pic_name = ''
            print e.img.attrs['src']
            if 'gif' in e.img.attrs['src']:
                pic_name = 'temp.gif'
            elif 'png' in e.img.attrs['src']:
                pic_name = 'temp.png'
            elif 'jpg' in e.img.attrs['src']:
                pic_name = 'temp.jpg'
            else:
                pic_name = 'temp.jpeg'
            urllib.urlretrieve(e.img.attrs['src'], filename=pic_name)
            document.add_picture(pic_name)
    except:
        pass
    if e.string:
        print e.string
        document.add_paragraph(e.string)
        
document.save("freebuf_article.docx")
print "success create a document"
예제 #47
0
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

document.add_picture('images/monty-truth.jpg', width=Inches(1.25))

document.add_heading('Table Examples', level=1)

table_types = [
  'Colorful Grid',
  'Colorful List',
  'Colorful Shading',
  'Dark List',
  'Light Grid',
  'Light List',
  'Light Shading',
  'Medium Grid 1',
  'Medium Grid 2',
  'Medium Grid 3',
  'Medium List 1',
예제 #48
0
파일: json2doc.py 프로젝트: derwarre/stuff
            for l3out in l3outs:
                document.add_paragraph(l3out, style='ListBullet')
        # Create image
        graph = pydot.Dot(graph_type='graph')
        for bd in bds:
            edge = pydot.Edge('VRF '+ vrf['attributes']['name'], 'BD ' + bd)
            graph.add_edge(edge)
            ips = getIpsForBD(fvBD, bd)
            for ip in ips:
                edge = pydot.Edge('BD ' + bd, ip)
                graph.add_edge(edge)
        for l3out in l3outs:
            edge = pydot.Edge('VRF ' + vrf['attributes']['name'], 'L3out ' + l3out)
            graph.add_edge(edge)
        graph.write_png(vrf['attributes']['name'] + '.png')
        document.add_picture(vrf['attributes']['name'] + '.png')


# Print a brief description of the L3outs
document.add_paragraph('', style='CodeStyle')
document.add_heading('External IP connections', level=2)
document.add_paragraph(' ', style='CodeStyle')
if l3extOut.__len__() == 0:
    document.add_paragraph('This tenant has no external IP connections (L3) defined: it is either isolated, or using a L2 connection to the outside world.', style='CodeStyle')
else:
    document.add_paragraph('This tenant has the following external IP connections defined:', style='CodeStyle')
    for l3out in l3extOut:
        paragraph='-   ' + l3out['attributes']['name']
        importsubnets = getImportSubnets(l3out)
        exportsubnets = getExportSubnets(l3out)
        contracts=getConsContractsL3out(l3out)
예제 #49
0
파일: genqr.py 프로젝트: wvanderp/project78
import qrcode

from docx import Document
from docx.shared import Inches

data = '90&2:'

img = qrcode.make(data)
img.save('qr.jpg')

document = Document()
document.add_picture('qr.jpg', width=Inches(6))
document.add_page_break()
document.save('demo.docx')
예제 #50
0
파일: a.py 프로젝트: today/forTangbo_py
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

document.add_picture('gdg-xian.png', width=Inches(2.5))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'

recordset = []
recordset.append( {'qty':'1','id':'ababab','desc':'xxxxxxxxxxx'})
recordset.append( {'qty':'1','id':'ababab','desc':'xxxxxxxxxxx'})
recordset.append( {'qty':'1','id':'ababab','desc':'xxxxxxxxxxx'})

for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item['qty'])
예제 #51
0
# coding: utf-8
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import sys
import os
DIR = os.path.dirname(os.path.abspath(__file__))

def name_of_pic(name):
    return os.path.join(DIR, name)

document = Document()

head=document.add_heading('Document Title', 0)
head.alignment = WD_ALIGN_PARAGRAPH.CENTER

names = os.listdir(DIR)
for name in names:
    if name.endswith('png') or name.endswith('PNG'):
        picture=document.add_picture(name_of_pic(name), width=Inches(1.25))
        last_paragraph = document.paragraphs[-1] 
        last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
        p=document.add_paragraph(' Add a comment to this picture ')
        p.alignment = WD_ALIGN_PARAGRAPH.CENTER

document.save(sys.argv[1])
예제 #52
0
파일: Mail.py 프로젝트: Adlav/scaling-guide
from docx.shared import Inches
from openpyxl import load_workbook


address = ""
trust =""
date =""
dear =""
intro =""
appt =""
outro =""
signature =""


book =  load_workbook('Sample.xlsx')
sheet1 = book.active
doc = Document()
data = []
for i in sheet1:
    for j in i:
        data.append(j.value)

print data

header = doc.sections[0]
header.add_paragraph('Hello')
doc.add_picture('Repselfie-Logo-B.png', width=None, height=None)
doc.add_paragraph('Dear ' + str(data[2]))
doc.add_paragraph('')
doc.save('sample.docx')
예제 #53
0
def OpenAndInitialiseDocX(filename):
    document = Document("Book Origami Template.docx")
    section = document.sections[0]
    #document.add_paragraph(filename)
    document.add_picture(filename, width=Mm(50))
    return document
예제 #54
0
document.add_heading('Overview', 1)

p = document.add_paragraph('')
p.add_run('Project Overview\n').bold = True
p.add_run('PBS has deployed the Endeca IAP solution that provides search, Guided Navigation, and dynamic merchandising functionality on the pbs.org site.PBS engaged with Thanx Media Professional Services for guidance Finish(of the Data Foundry and pipeline processes for the creation of the indices that is utilized by the sites).  The user interface portion and control scripts for the application were developed by PBS to interact with the MDEX Engine through the Endeca Assembler API.')
p.add_run('\n\nAbout the Technical Specification Document\n').bold = True
p.add_run('The purpose of this document is to outline the implementation details for the Endeca IAP instance reflecting the requirements defined through a Requirements Workshop and subsequently captured in the PBS Business Requirements document.  The Technical Specification document contains information about Endeca, index creation, custom scripts, and operational processes through control scripts and the Endeca Workbench.')

document.add_heading('Overview of Endeca Technology', 1)

p = document.add_paragraph('')
p.add_run('Endeca Architecture Overview\n').bold = True
p.add_run('The basic Endeca Architecture consists of four (4) main parts as illustrated in the diagram: the Endeca Data Foundry (EDF), the Endeca MDEX Engine (MDEX), the Endeca Application Controller (EAC), and the Endeca API.')

document.add_picture('C:/Daniel/techSpectoDoc/template/architectureOverview.png', width=Inches(3.25))

p = document.add_paragraph('')
p.add_run('Endeca Data Foundry (EDF)\n').bold = True
p.add_run('The EDF is an offline process that first reads in the source data and application specific configuration files.  Using the instructions outlined in the configuration files; the EDF transforms the raw data into structured data and indexes it.  The output of the EDF is a set of indices (binary and xml files) which are provided to the Endeca MDEX Engines.  This is typically a scheduled offline process that runs, and therefore happens independently of the MDEX Engines handling the runtime queries.')
p.add_run('\n\nEndeca MDEX Engine (MDEX)\n').bold = True
p.add_run('The MDEX is an online server that listens on a specific port for HTTP requests, and responds by returning binary results.  Once a new set of indices is created from the EDF, the MDEX will load the indices into memory at process restart.  The MDEX is also stateless, with no concept of a session object for each user.  This allows multiple MDEX engines with the same set of indices to return the same results, allowing for easy scalability and redundancy behind a load balancer.')
p.add_run('\n\nEndeca Application Controller\n').bold = True
p.add_run('The Endeca Application Controller consists of the Central Server and Agents.  The EAC is installed and runs on the primary Endeca server, creating a single interface for coordinating jobs across all machines.  Agents are installed on each Endeca server and are responsible for the actual work of an Endeca implementation.  Communication to these agents is performed through the EAC Central Server via eaccmd, a command line interface, or Workbench.')
p.add_run('\n\nEndeca API\n').bold = True
p.add_run('The Endeca Presentation Layer Java API can be installed on any application server that supports Java.  The API is used to create and send the query to the MDEX Engine over HTTP.  It receives the response as a binary encoded result object and uses the appropriate methods and objects to display the information in the UI.  The query must be submitted to a pre-defined host and port.  If only one MDEX engine exists, the host and port of the MDEX engine should be configured at the UI level.  If multiple MDEX engines exist behind a load balancer, the host and port of the load balancer should be configured at the UI level. ')
p.add_run('\n\nImplementation Architecture\n').bold = True
p.add_run('Architecture of the Endeca cluster will follow the Oracle Endeca best practice of Authoring/Live clusters. Authoring environments will be run with Live data, and will serve as the Endeca Workbench test platform. An overview of the environment can be found in section 16. ')

document.add_heading('Data Definition', 1)
예제 #55
0
def download_file_function(projectID):
    blockUsers()
    """Download checklist results report in docx"""
    if not session.get('logged_in'):
        log("User with no valid session tries access to page /results-function-docx", "FAIL", "HIGH")
        abort(401)
    content_raw = []
    content_title = []
    content_tech = []
    valNum(projectID)
    safe_id = encodeInput(projectID)
    db = get_db()
    cur = db.execute("SELECT projects.projectName, projects.projectID, projects.projectVersion, parameters.functionName, parameters.tech, parameters.functionDesc, parameters.entryDate, parameters.techVuln, techhacks.techName, projects.userID FROM projects JOIN parameters ON parameters.projectID=projects.projectID JOIN techhacks ON techhacks.techID  = parameters.tech WHERE parameters.projectID=? AND projects.userID=? GROUP BY parameters.tech;",
               [safe_id, session['userID']])
    entries = cur.fetchall()
    document = Document()
    document.add_picture(os.path.join(app.root_path,'static/img/banner-docx.jpg'), width=Inches(5.125), height=Inches(1.042))
    last_paragraph = document.paragraphs[-1] 
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
    #document.add_heading('Security Knowledge Framework', 0)
    last_paragraph = document.paragraphs[-1] 
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p = document.add_paragraph()
    projectName = entries[0][0]
    functionName = entries[0][3]
    functionDesc= entries[0][5]
    p.add_run('Date: '+datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    p.add_run('\r\n')
    p.add_run('Project: '+projectName)
    document.add_page_break()
    p = document.add_heading('Table of contents', level=1)
    p.add_run('\r\n')
    document.add_paragraph('Introduction')
    for entry in entries:
        entryDate = entry[6]
        vulnID = entry[7]
        full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/knowledge_base"))
        for path in full_file_paths:
            org_path = path
            path = path.split("markdown")
            path_vuln = get_num(path[1])
            if int(vulnID) == int(path_vuln):
                filemd = open(org_path, 'r').read()
                content = Markup(markdown.markdown(filemd))
                text = ''.join(BeautifulSoup(content).findAll(text=True))
                text_encode = text.encode('utf-8')
                content_title.append(text_encode.splitlines()[0])
                text_encode = text_encode.replace("Solution", "\nSolution");
                content_raw.append(text_encode)
    for item in content_title:
        p = document.add_paragraph(item)
        p.add_run()
    document.add_page_break()
    document.add_heading('Introduction', level=1)
    p = document.add_paragraph(
        'The security knowledge framework is composed by means of the highest security standards currently available and is designed to maintain the integrity of your application, so you and your costumers sensitive data is protected against hackers. This document is provided with a checklist in which the programmers of your application had to run through in order to provide a secure product.'
    )
    p.add_run('\n')
    p = document.add_paragraph(
        'In this part of security knowledge framework, al the parameters and variables are audited by means of the information given by the programmer such as the processing techniques. Each of these techniques contain different types of vulnerabilities when implemented in a improper fashion. This document will raise awareness about these vulnerabilities, as well as presenting solutions for the right implementation.'
    )
    document.add_page_break()
    i = 0
    for item in content_raw:
        document.add_heading("Knowledge-Base: "+content_title[i], level=1)
        document.add_heading("Technology: "+entries[i][8], level=2)
        p = document.add_paragraph(item.partition("\n")[2])
        p.add_run("\n")
        document.add_page_break()
        i += 1
    document.save('function-security-report.docx')
    headers = {"Content-Disposition": "attachment; filename=%s" % "function-security-report.docx"}
    with open("function-security-report.docx", 'rb') as f:
        body = f.read()
    return make_response((body, headers))
예제 #56
0
def download_file_checklist(entryDate):
    blockUsers()
    """Download checklist results report in docx"""
    if not session.get('logged_in'):
        log("User with no valid session tries access to page /results-checklist-docx", "FAIL", "HIGH")
        abort(401)
    ygb_docx = []    
    content_raw = []
    content_checklist = []
    content_title = []
    safe_entryDate = encodeInput(entryDate)
    db = get_db()
    cur = db.execute("SELECT * FROM questionlist WHERE answer='no' AND entryDate=? AND userID=?",
               [safe_entryDate, session['userID']])
    entries = cur.fetchall()
    document = Document()
    document.add_picture(os.path.join(app.root_path,'static/img/banner-docx.jpg'), width=Inches(5.125), height=Inches(1.042))
    last_paragraph = document.paragraphs[-1] 
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT
    #document.add_heading('Security Knowledge Framework', 0)
    last_paragraph = document.paragraphs[-1] 
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p = document.add_paragraph()
    projectName = entries[0][3]
    listName = entries[0][6]
    ygb = False
    p.add_run('Used Checklist: '+listName)
    p.add_run('\r\n')
    p.add_run('Date: '+datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
    p.add_run('\r\n')
    p.add_run('Project: '+projectName)
    document.add_page_break()
    p = document.add_heading('Table of contents', level=1)
    p.add_run('\r\n')
    document.add_paragraph('Introduction')
    for entry in entries:
        projectName = entry[3]
        questionID = entry[4]
        vulnID = entry[5]
        listName = entry[6]
        entryDate = entry[7]
        full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/knowledge_base"))
        for path in full_file_paths:
            org_path = path
            path = path.split("markdown")
            path_vuln = get_num(path[1])
            if int(vulnID) == int(path_vuln):
                filemd = open(org_path, 'r').read()
                content = Markup(markdown.markdown(filemd))
                text = ''.join(BeautifulSoup(content).findAll(text=True))
                text_encode = text.encode('utf-8')
                content_title.append(text_encode.splitlines()[0])
                text_encode = text_encode.replace("Solution", "\nSolution");
                content_raw.append(text_encode)
                full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/checklists"))
                for path in full_file_paths:
                    org_path = path
                    path = path.split("markdown")
                    tmp_path = path[1].split("-")
                    custom_path = get_num(tmp_path[0])
                    path_questionID = custom_path
                    if int(questionID) == int(path_questionID):
                        filemd = open(org_path, 'r').read()
                        content_checklist.append(Markup(markdown.markdown(filemd)))
                        custom_paths = org_path.split("-")
                        found = custom_paths[3].find("ASVS")
                        if found != -1:
                            ygb = True
                            ygb_docx.append(custom_paths[9])
    for item in content_title:
        p = document.add_paragraph(item)
        p.add_run()
    document.add_page_break()
    document.add_heading('Introduction', level=1)
    p = document.add_paragraph(
        'The security knowledge framework is composed by means of the highest security standards currently available and is designed to maintain the integrity of your application, so you and your costumers sensitive data is protected against hackers. This document is provided with a checklist in which the programmers of your application had to run through in order to provide a secure product.'
    )
    p.add_run('\n')
    p = document.add_paragraph(
        'In the post-development stage of the security knowledge framework the developer double-checks his application against a checklist which consists out of several questions asking the developer about different stages of development and the methodology of implementing different types of functionality the application contains. After filling in this checklist the developer gains feedback on the failed checklist items providing him with solutions about how to solve the additional vulnerability\'s found in the application.'
    )
    document.add_page_break()
    i = 0
    for item in content_raw:
        document.add_heading(content_title[i], level=1)
        result = re.sub("<p>", " ", content_checklist[i])
        result1 = re.sub("</p>", " ", result)
        document.add_heading(result1, level=4)
        p = document.add_paragraph(item.partition("\n")[2])
        if ygb == True:
            if ygb_docx[i] == "b":
                image = document.add_picture(os.path.join(app.root_path,'static/img/blue.png'), width=Inches(0.20))
            elif ygb_docx[i] == "gb":
                image = document.add_picture(os.path.join(app.root_path,'static/img/green.png'), width=Inches(0.20))
                image = document.add_picture(os.path.join(app.root_path,'static/img/blue.png'), width=Inches(0.20))
            elif ygb_docx[i] == "ygb":
                image = document.add_picture(os.path.join(app.root_path,'static/img/yellow.png'), width=Inches(0.20))
                image = document.add_picture(os.path.join(app.root_path,'static/img/green.png'), width=Inches(0.20))            
                image = document.add_picture(os.path.join(app.root_path,'static/img/blue.png'), width=Inches(0.20))
        p.add_run("\n")
        document.add_page_break()
        i += 1
    document.save("checklist-security-report.docx")
    headers = {"Content-Disposition": "attachment; filename=%s" % "checklist-security-report.docx"}
    file_path = os.path.join(app.root_path, "checklist-security-report.docx")
    with open("checklist-security-report.docx", 'rb') as f:
        body = f.read()
    return make_response((body, headers))
예제 #57
0
    run2.italic = True

    t = document.add_table(rows=2, cols=2)
    t.cell(0, 0).text = u'单元1'
    t.cell(0, 1).text = u'单元2'
    t.cell(1, 0).text = u'单元3'
    t.cell(1, 1).text = u'单元4'

    t = document.add_table(rows=2, cols=2)
    merge_cell = t.cell(0, 0).merge(t.cell(0, 1))
    merge_cell.text = u'合并单元格'

    t = document.add_table(rows=2, cols=2)
    t.style = 'Table Grid'

    document.add_picture("./media/logo_for_1.png")
    img_url = "http://zeromq.wdfiles.com/local--files/admin:css/logo.gif"
    image_from_url = urllib2.urlopen(img_url)
    io_url = StringIO.StringIO()
    io_url.write(image_from_url.read())
    io_url.seek(0)
    document.add_picture(io_url)

    # print "console------"
    # print len(document.styles)
    # for s in document.styles:
    #     print s.name
    
    new_section = document.add_section(WD_SECTION.ODD_PAGE)
    
    document.save('./store/foo.docx')
예제 #58
0
def convert_to_docx(output_dir, tmp_dir, md_file, args):

    md_path = tmp_dir / md_file
    if not md_path.exists():
        return

    j = Journal(args.journal_json)

    document = Document(str(args.ref_docx))

    docx_path = output_dir / md_path.with_suffix('.docx').name

    first_fig = True
    first_table = True

    with md_path.open(encoding='utf-8') as f:

        p = None

        for md in f.read().split('\n'):

            if md.startswith('# '):
                document.add_heading(md[2:], 0)

            elif md.startswith('## '):
                section_name = md[3:]
                if j.has_newpage(section_name):
                    document.add_page_break()
                document.add_heading(md[3:], 1)

            elif md.startswith('### '):

                if md.startswith('### Table '):
                    if first_table:
                        # no new page for the first table
                        first_table = False

                    else:
                        document.add_page_break()

                cond_f0 = j.embed_figures() or args.embed
                cond_f1 = md.startswith('### Figure ')
                if cond_f0 and cond_f1:
                    if first_fig:
                        # no new page for the first fig
                        first_fig = False

                    else:
                        document.add_page_break()

                document.add_heading(md[4:], 2)

            elif md.startswith('![]('):
                path_to_img = md[4:-1]  # TODO: cleaner way to select path
                document.add_picture(path_to_img)

            elif len(md) > 0 and md[0] == '^' and md[-1] == '^':  # table header
                n_col = md.count('^') - 1
                table = document.add_table(rows=1, cols=n_col)
                table.autofit = True
                row_cells = table.rows[0].cells
                for one_cell, txt in zip(row_cells, md.split('^')[1:-1]):
                    one_cell.paragraphs[0].add_run(txt.strip()).bold = True

            elif len(md) > 0 and md[0] == '|' and md[-1] == '|':
                row_cells = table.add_row().cells

                for one_cell, txt in zip(row_cells, md.split('|')[1:-1]):
                    one_cell.text = txt.strip()

            elif md.strip() == '':  # empty line, i.e. end of the paragraph
                p = None

            else:
                if p is None:
                    if md.startswith('>'):
                        style = 'Reviewer'
                        md = md[2:]  # remove "> " at the beginning
                    else:
                        style = None
                    p = document.add_paragraph(style=style)
                else:
                    p.add_run(' ')

                _add_run(p, md)

    document.save(str(docx_path))
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'


class records(object):
    def __init__(self, Qty=-1, Ids=-1, Desc=None):
        self.qty = Qty
        self.id = Ids
        self.desc = Desc

r1 = records(1, 101, 'Spam')