欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 保存Log txt信息,并转成pdf,支持中文

程序员文章站 2022-03-02 13:04:36
...
# coding=UTF-8
    import  os
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont

    pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttf'))

    def LogMessage( msg, bisLogMsg=True):
        savingmsg = ''
        savingmsg = savingmsg + QtCore.QDate.currentDate().toString("yyyy-MM-dd")
        savingmsg = savingmsg + ' ' + QtCore.QTime.currentTime().toString("HH:mm:ss")
        savingmsg = savingmsg + ' ' + msg
        if bisLogMsg:
            savingLogMsg(savingmsg)
        else:
            savingResultMsg(savingmsg)

    def savingLogMsg(self, logmsg):
        if not os.path.exists('./log'):
            os.makedirs('./log')
        self.savingtxtmsg = open('./log/autotlog.txt', 'a')
        self.savingtxtmsg.write(logmsg)
        self.savingtxtmsg.write('\n')
        self.savingtxtmsg.close()
    def savingResultMsg(resultmsg):
        if not os.path.exists('./log'):
            os.makedirs('./log')
        savingtxtmsg = open('./log/result.txt', 'a')
        savingtxtmsg.write(resultmsg)
        savingtxtmsg.write('\n')
        savingtxtmsg.close()
        TxtToPdf('./log/result.txt','./log/result.pdf')

    def TxtToPdf(strSourceTxt,strTargetPdf):
        ptr = open(strSourceTxt, "r")  # text file I need to convert
        lineas = ptr.readlines()
        ptr.close()

        numeroLinea = 0
        p = Canvas(strTargetPdf)
        while numeroLinea < len(lineas):
            i = 750
            for linea in lineas[numeroLinea:numeroLinea + 60]:
                if 'fail' in linea:
                    p.setFont('msyh', 10)
                    p.setFillColorRGB(0, 0, 0.77)
                else:
                    p.setFont('msyh', 8)
                    p.setFillColorRGB(0, 0, 0)
                p.drawString(15, i, linea.strip())
                numeroLinea += 1
                i -= 12
            p.showPage()

        p.save()
LogMessage('Save System State: pass', False)