reportlab垂直码条代码39

时间:2017-05-24 11:43:15

标签: python reportlab

从带有python的reportlab开始,这是我的小医疗应用程序的最后一步。

我无法找到一种工作解决方案,用于在为其设计的框架中设置垂直条形码(侧面薄框架)。其他一切都还可以(文件由五个框架,桌子,其他条形码组成)。 也许框架没用,但我怎么能这样做呢?

想法? 感谢。

这是我可怕的代码,对不起,我正在研究它。

#!/usr/bin/python
# coding: utf-8

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Frame, PageTemplate, BaseDocTemplate, FrameBreak, Table, TableStyle, KeepInFrame
from reportlab.graphics.barcode import code39 
from reportlab.pdfgen import canvas
from reportlab.platypus.flowables import Flowable
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import cm
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
from reportlab.lib.colors import black, purple, white, yellow, blue, darkblue

class verticalText(Flowable):
    ''' Rotate a text in a tabe cell '''
    def __init__(self, text):
        Flowable.__init__(self)
        self.text = text

    def draw(self):
        canvas = self.canv
        canvas.rotate(90)
        #fs = canvas._fontsize
        #canvas.translate(1, -fs/1.2)
        canvas.drawString(0, -1, self.text)

    #def wrap(self, aW, aH):
        #canv = self.canv
        #fn, fs = canv._fontname, canv._fontsize
        #return canv._leading, 1 + canv.stringWidth(self.text, fn ,fs)

class pdf():
    def __init__(self, _filename, _lignes_redigees):

        #VERROUS
        self.verBIZONE = False

        #PREPARATION DES DONNES TRANSMISES
        self.lignes_redigees = _lignes_redigees

        rpps = "10100167890"
        noordo = "20170524130651"

        #code barres rpps
        self.rpps_barcode = code39.Extended39(rpps)
        #code barre ordo
        self.noordo_barcode = code39.Extended39(noordo+rpps)


        vdoc = [['TITRE PRENOM NOM'], 
                ['DATADATADATADATADATADATADATADATA'], 
                ['DATADATADATADATADATADATADATADATA'],
                ['DATADATADATADATADATADATADATADATADATADATADATADATA'],
                [self.rpps_barcode],
                ['DATADATADATADATADATADATADATADATA']]

        vpat = [["TITRE PRENOM NOM"], ["DATADATADATADATADATADATADATADATA"], ["DATADATADATADATA"]]

        self.data_datelieu = "Toulouse, le 22 mai 2017"
        self.__preparation_des_data_lignes_redigees()

        # PDF Properties
        self.Title = "Ordonnance"
        self.Author = "DATADATADATADATA"
        self.PageInfo = "-"
        p_h = 29.7 #page height
        p_w = 21   #page width
        h_m = 1    #marges hauteur
        w_m = 1    #marges largeur
        entetes_h = 5.3
        datelieu_h = 1

        #coo frame Side
        side_x1 = w_m; side_y1 = h_m; side_h = p_h - 2*h_m ; side_w = 1
        #coo frame doc
        doc_x1 = side_x1 + side_w ; doc_y1 = p_h - h_m - entetes_h ; doc_w = (p_w - 2*w_m - side_w)/2 ; doc_h = entetes_h
        #coo frame pat
        pat_x1 = side_x1 + side_w + doc_w ; pat_y1 = p_h - h_m - entetes_h ; pat_w = doc_w ; pat_h = doc_h
        #coo frame date lieu
        dl_x1 = side_w + w_m ; dl_y1 = p_h - h_m - entetes_h - datelieu_h ; dl_w = p_w - 2*w_m - side_w; dl_h = datelieu_h 
        #coo frame pres
        pr_x1 = side_w + w_m ; pr_y1 = h_m ; pr_w = dl_w; pr_h = p_h - 2*h_m - entetes_h - datelieu_h
        self.pres_w = pr_w

        # define frames - for frames in page
        self.frSide = Frame(x1=side_x1*cm, y1=side_y1*cm, width=side_w*cm, height=side_h*cm, 
                            leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
        self.frMedecin = Frame(x1=doc_x1*cm, y1=doc_y1*cm, width=doc_w*cm, height=doc_h*cm, showBoundary=1,
                            leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
        self.frPatient = Frame(x1=pat_x1*cm, y1=pat_y1*cm, width=pat_w*cm, height=pat_h*cm, 
                            leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
        self.frDateLieu = Frame(x1=dl_x1*cm, y1=dl_y1*cm, width=dl_w*cm, height=dl_h*cm, 
                            leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
        self.frPres = Frame(x1=pr_x1*cm, y1=pr_y1*cm, width=pr_w*cm, height=pr_h*cm, 
                            leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)

        # define pageTemplates - for page in document
        self.mainPage = PageTemplate(pagesize=A4, frames=[self.frSide, self.frMedecin, self.frPatient, self.frDateLieu,
                                                          self.frPres])

        # define BasicDocTemplate - for document
        self.doc = BaseDocTemplate(_filename, pagesize=A4, pageTemplates=self.mainPage, title=self.Title,
                                   author=self.Author, showBoundary=0)

        # styles
        self.styles = self.__init_stylesheet()
        self.standard_styles = getSampleStyleSheet()
        self.stylePat = self.standard_styles['Normal']
        # i don't use it, not more than paragraphs
        self.styleDoc = ParagraphStyle('hdoc')
        self.styleDoc.defaults['borderColor'] = '#000000'
        self.styleDoc.defaults['borderWidth'] = '1'

        self.styleDL = self.styles['hdatelieu']

        #create tables
        self.doc_table = Table(vdoc, colWidths=doc_w*cm)
        self.doc_table.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'CENTER'),
                                       ('TEXTCOLOR', (0,0), (-1,-1), darkblue),
                                       ('FONT', (0,0), (0,0),'Times-Bold', 15),
                                       ('FONT', (0,1), (-1,-1), 'Times-Roman', 13)]))
        self.pat_table = Table(vpat, colWidths=pat_w*cm, vAlign='TOP')
        self.pat_table.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'CENTER'),
                                       ('TEXTCOLOR', (0,0), (-1,-1), black),
                                       ('FONT', (0,1), (-1,-1), 'Courier-Bold', 11),
                                       ('FONT', (0,0), (0,0), 'Courier-Bold', 13)]))

        #preparing prescription tables
        self.__prepare_les_séparateurs_ald()
        self.__preparation_des_tables_de_ligne()

        #process
        self._process()     

    def __init_stylesheet(self): #i don't use it, not more than paragraphs, it was for studying
        styles= {'default': ParagraphStyle('default',
                                            fontName='Times-Roman',
                                            fontSize=10,
                                            leading=12,
                                            leftIndent=0,
                                            rightIndent=0,
                                            firstLineIndent=0,
                                            alignment=TA_LEFT,
                                            spaceBefore=0,
                                            spaceAfter=0,
                                            bulletFontName='Times-Roman',
                                            bulletFontSize=10,
                                            bulletIndent=0,
                                            textColor= black,
                                            backColor=None,
                                            wordWrap=None,
                                            borderWidth= 0,
                                            borderPadding= 0,
                                            borderColor= None,
                                            borderRadius= None,
                                            allowWidows= 1,
                                            allowOrphans= 0,
                                            textTransform=None,  # 'uppercase' | 'lowercase' | None
                                            endDots=None,         
                                            splitLongWords=1,
                                        )}

        styles['hdoc'] = ParagraphStyle('hdoc', parent=styles['default'],
            fontName='Helvetica-Bold',
            fontSize=12,
            leading = 17,
            borderColor=black,
            borderWidth=1, 
            borderPadding = 0.5*cm,
            alignment=TA_CENTER,
            wordWrap = 'LTR',
            textColor=darkblue)

        styles['hpat'] = ParagraphStyle('hpat', parent=styles['default'],
            fontName='Helvetica',
            fontSize=12,
            alignment=TA_CENTER,
            textColor=black)

        styles['hdatelieu'] = ParagraphStyle('hdatelieu', parent=styles['default'],
            fontName='Helvetica',
            fontSize=12,
            alignment=TA_RIGHT,
            borderColor=black,
            borderWidth=1,            
            borderPadding = 0,
            textColor=black)        

        return styles


    def __prepare_les_séparateurs_ald(self):

        p_ald = [["Prescription(s) relative(s) au traitement de l'affection de longue durée reconnue, (liste ou hors liste)"],
                 ["(AFFECTION EXONERANTE)"]]
        p_nald = [["Prescription(s) SANS RAPPORT avec l'affection de longue durée"],
                  ["(MALADIES INTERRECURRENTES)"]]

        self.t_ald = Table(p_ald, colWidths=self.pres_w*cm)
        self.t_ald.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'CENTER'),
                                   ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                                   ('TEXTCOLOR', (0,0), (-1,-1), black),
                                   ('FONT', (0,0), (-1,-1),'Helvetica', 11),
                                   ('LINEABOVE', (0,0), (0,0), 1, black),
                                   ('LINEBELOW', (-1,-1), (-1,-1), 1, black)]))

        self.t_nald = Table(p_nald, colWidths=self.pres_w*cm)
        self.t_nald.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'CENTER'),
                                   ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                                   ('TEXTCOLOR', (0,0), (-1,-1), black),
                                   ('FONT', (0,0), (-1,-1),'Helvetica', 11),
                                   ('LINEABOVE', (0,0), (0,0), 1, black),
                                   ('LINEBELOW', (-1,-1), (-1,-1), 1, black)]))

    def __preparation_des_data_lignes_redigees(self):
        #prepare data for platypus tables
        self.data_lignes_redigees = []

        #first look for ALD prescription
        for ligne in self.lignes_redigees:
            if ligne[-1] == 'A.L.D.':
                self.verBIZONE = True


        if self.verBIZONE == False :
            x = 0
            for ligne in self.lignes_redigees:
                x +=1 
                bloc_data=[]
                i=0
                for item in ligne:
                    i += 1
                    if i == 1 : j = str(x)+'.'
                    else : j = ""
                    bloc_data.append([j,item])
                self.data_lignes_redigees.append(bloc_data)
                print('blocdata', self.data_lignes_redigees)

        else:
            self.data_lignes_redigees_ald = []
            self.data_lignes_redigees_nald = []

            x = 0
            for ligne in self.lignes_redigees:
                if ligne[-1] == 'A.L.D.':
                    x +=1 
                    bloc_data=[]
                    i=0
                    for item in ligne:
                        i += 1
                        if i == 1 : j = str(x)+'.'
                        else : j = ""
                        if item != 'A.L.D.': bloc_data.append([j,item])
                    self.data_lignes_redigees_ald.append(bloc_data)
                    print('blocdata_ald', self.data_lignes_redigees_ald) 

            for ligne in self.lignes_redigees:
                if ligne[-1] != 'A.L.D.':
                    x +=1 
                    bloc_data=[]
                    i=0
                    for item in ligne:
                        i += 1
                        if i == 1 : j = str(x)+'.'
                        else : j = ""
                        bloc_data.append([j,item])
                    self.data_lignes_redigees_nald.append(bloc_data)
                    print('blocdata_ald', self.data_lignes_redigees_nald)


    def __preparation_des_tables_de_ligne(self):               
        #prepare les tables

        self.story_tables_pres = []
        self.story_tables_pres_ald = []

        if self.verBIZONE == False:
            for data_ligne in self.data_lignes_redigees:
                tablep = Table(data_ligne, 
                               colWidths=(1*cm, self.pres_w*cm - 1*cm),
                               rowHeights = [1*cm] + [0.5*cm]*(len(data_ligne)-1))

                tablep.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'LEFT'),
                                            ('ALIGN', (0,0), (0,-1), 'RIGHT'),
                                           ('TEXTCOLOR', (0,0), (-1,-1), black),
                                           ('FONT', (0,0), (-1,0),'Helvetica-Bold', 12),
                                           ('FONT', (0,1), (-1,-1), 'Helvetica', 11)]))

                self.story_tables_pres.append(tablep)

        if self.verBIZONE == True:
            for data_ligne in self.data_lignes_redigees_ald:
                tablep = Table(data_ligne, 
                               colWidths=(1*cm, self.pres_w*cm - 1*cm),
                               rowHeights = [1*cm] + [0.5*cm]*(len(data_ligne)-1))

                tablep.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'LEFT'),
                                            ('ALIGN', (0,0), (0,-1), 'RIGHT'),
                                           ('TEXTCOLOR', (0,0), (-1,-1), black),
                                           ('FONT', (0,0), (-1,0),'Helvetica-Bold', 12),
                                           ('FONT', (0,1), (-1,-1), 'Helvetica', 11)]))

                self.story_tables_pres_ald.append(tablep)

            for data_ligne in self.data_lignes_redigees_nald:
                tablep = Table(data_ligne, 
                               colWidths=(1*cm, self.pres_w*cm - 1*cm),
                               rowHeights = [1*cm] + [0.5*cm]*(len(data_ligne)-1))

                tablep.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'LEFT'),
                                            ('ALIGN', (0,0), (0,-1), 'RIGHT'),
                                           ('TEXTCOLOR', (0,0), (-1,-1), black),
                                           ('FONT', (0,0), (-1,0),'Helvetica-Bold', 12),
                                           ('FONT', (0,1), (-1,-1), 'Helvetica', 11)]))

                self.story_tables_pres.append(tablep)




    def _process(self):

        #Story
        self.story = []
        #self.story.append(verticalText(self.noordo_barcode))
        self.story.append(FrameBreak())


        self.kept_doc_st = []
        self.kept_doc_st.append(self.doc_table)
        kept_doc = KeepInFrame(0,0 ,self.kept_doc_st, mode='shrink', hAlign='CENTER', vAlign='MIDDLE', fakeWidth=False)

        self.story.append(kept_doc)
        self.story.append(FrameBreak())

        self.kept_pat_st = []
        self.kept_pat_st.append(self.pat_table)
        kept_pat = KeepInFrame(0,0 ,self.kept_pat_st, mode='shrink', hAlign='CENTER', vAlign='MIDDLE', fakeWidth=False)

        self.story.append(kept_pat)
        self.story.append(FrameBreak())

        hd = Table([[self.data_datelieu]], colWidths=self.pres_w*cm, rowHeights=1*cm)
        hd.setStyle(TableStyle([('ALIGN', (0,0), (-1,-1), 'RIGHT'),
                                ('TEXTCOLOR', (0,0), (-1,-1), black),
                                ('FONT', (0,0), (-1,-1), 'Courier-Bold', 11),
                                ('VALIGN', (0,0), (-1,-1), 'MIDDLE')]))
        self.story.append(hd)
        self.story.append(FrameBreak())


        #mise en place du bloc de prescription
        if self.verBIZONE == False:
            for e in self.story_tables_pres:
                self.story.append(e)
        if self.verBIZONE == True:
            self.story.append(self.t_ald)
            for e in self.story_tables_pres_ald:
                self.story.append(e)
            self.story.append(self.t_nald)
            for e in self.story_tables_pres:
                self.story.append(e)            


        #finallement
        self.doc.build(self.story)


if __name__ == '__main__':

    lignes=[['(cétirizine), 10 mg, cp', 'Prendre 1 cp le matin', 'A.L.D.'],
            ['DEROXAT (paroxétine), 20 mg, cp', 'Si besoin prendre 1 cp le matin', 'si envie', 'A.L.D.']]


    app = pdf('test.pdf', lignes)

2 个答案:

答案 0 :(得分:0)

好的,我设法用这个做了一些拼凑:

http://nullege.com/codes/search/reportlab.graphics.barcode.createBarcodeDrawing

我没有使用文字和字体制作条形码,而是将其转换成易于旋转的图形(旋转方法)。

答案 1 :(得分:0)

这出奇的简单。您只需要旋转和平移条形码下方的画布并交换其宽度和高度。因此,我继承了原始类并更改了 wrapdraw 方法。

from reportlab.graphics.barcode.code39 import Extended39


class VerticalCode39(Extended39):
    def wrap(self, *args, **kwargs):
        w, h = super().wrap(*args, **kwargs)
        return h, w

    def draw(self):
        self.canv.rotate(90)
        self.canv.translate(0, -self.barHeight)
        super().draw()

VerticalCode39 的用法与 Extended39 相同。