def put_corner_left_data(self, pdf): pdf.drawInlineImage(self.image, 100, 720, width=125, height=120) frame1 = Frame(50, 670, 220, 50) pa = Paragraph(self.object.company_id.name, self.style_own14) story_inframe = KeepInFrame(220, 70, [pa], hAlign='CENTER', vAlign='MIDDLE') frame1.addFromList([story_inframe], pdf) pdf.setFont('Times-Bold', 10) pdf.drawString(60, 680, 'Direccion:') pdf.setFont('Times-Roman', 10) frame2 = Frame(110, 646, 150, 50) pa = Paragraph(self.object.company_id.street, self.style_own10) story_inframe = KeepInFrame(150, 70, [pa], hAlign='CENTER', vAlign='MIDDLE') frame2.addFromList([story_inframe], pdf) pdf.setFont('Times-Bold', 10) pdf.drawString(60, 655, 'Telefono:') pdf.setFont('Times-Roman', 10) pdf.drawString(120, 655, self.object.company_id.phone) if self.object.company_id.must_account: pdf.drawString(60, 635, 'OBLIGADO A LLEVAR CONTABILIDAD') pdf.drawString(100, 615, self.object.company_id.email) pdf.rect(50, 600, 220, 115) return pdf
def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight
def __init__(self, content=[], maxWidth=0, maxHeight=0, zoom=1, **kwargs): if content and not hasattr(content, "__iter__"): raise ValueError("content expected to be a list of flowables") self.zoom = zoom KeepInFrame.__init__(self, maxWidth, maxHeight, content=content, **kwargs)
def keep_in_frame(self, widget, width, height, paragraphs, mode, persistent=False): keep = KeepInFrame(width, height, paragraphs, mode=mode) keep.canv = self.canvas keep.wrap(self.calculate_size(widget.width), self.calculate_size(widget.height)) if persistent: widget.keep = keep return keep
def createHeader(self, canvas, doc): """ Criando o Primeira pagina do Documento """ self.c = canvas normal = self.styles["Normal"] center = self.styles['Center'] imgLeft = get_image(self.get_path_institute_congress(), height=100) imgLeft._restrictSize(40 * mm, 20 * mm) frameLeft = Frame( *self.coord(10 * mm, 30 * mm), 50 * mm, 20 * mm, ) ldata = [imgLeft] frameLeft.addFromList(ldata, self.c) frameCenter = Frame( *self.coord(60 * mm, 30 * mm), 90 * mm, 20 * mm, ) title_header_text = "<strong>{}</strong>".format(self.title) subtitle_header_text = "{}".format(self.subtitle) ptitle = KeepInFrame(85 * mm, 15 * mm, [Paragraph(title_header_text, center)]) psubtitle = KeepInFrame(85 * mm, 10 * mm, [Paragraph(subtitle_header_text, center)]) mdata = [ptitle, psubtitle] frameCenter.addFromList(mdata, self.c) imgRight = get_image(self.get_path_logo_congress(), width=100) imgRight._restrictSize(40 * mm, 20 * mm) frameRight = Frame( *self.coord(150 * mm, 30 * mm), 50 * mm, 20 * mm, ) rdata = [imgRight] frameRight.addFromList(rdata, self.c) date_header_text = "<font size='6'>Data: {}</font>".format( self.date.strftime("%d/%m/%Y")) pdata = Paragraph(date_header_text, normal) pdata.wrapOn(self.c, self.width, self.height) pdata.drawOn(self.c, *self.coord(self.width - 30 * mm, 38 * mm)) self.addPageNumber(canvas, doc)
def draw(self): pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 10 style.alignment = TA_JUSTIFY self.canv.saveState() data_text = [Paragraph(f'{self.text}', self.style)] if self.tbl: data_text = [self.tbl] data_frame = Frame(self.x * mm, self.y, self.width * mm, self.height * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) data_inframe = KeepInFrame( self.width * mm, self.height * mm, data_text, vAlign='TOP', fakeWidth=False, ) data_frame.addFromList([data_inframe], self.canv) self.canv.restoreState()
def wrap(self, awidth, aheight): self.maxHeight = aheight self.maxWidth = awidth w, h = KeepInFrame.wrap(self, awidth, aheight) if w < awidth and h < aheight: self._scale = max(w / awidth, h / aheight) return w, h
def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight
def write(self, outputFile): """Writes the modified pdf to a file. This method merges the original pdf with all of the added text fields together to create the final modified pdf. Text fields are written over top of the original pdf. Args: outputFile (str or file): Output file to write to. Can be string path or any file-like object. Returns: None """ # iterate through original pdf pages output = PdfFileWriter() for pagenum in range(self.pdf.numPages): existing_page = self.pdf.getPage(pagenum) # insert text fields if any for this page if len(self[pagenum]) > 0: mediaBox = self.pdf.getPage(pagenum).mediaBox pagesize = (mediaBox[2] - mediaBox[0], mediaBox[3] - mediaBox[1]) packet = BytesIO() canvas = Canvas(packet, pagesize=pagesize) if self.boxes: canvas.setStrokeColorRGB(*self.boxes) for field in self[pagenum]: frame = Frame(field.x1, field.y1, field.width, field.height, *field.padding, showBoundary=bool(self.boxes)) style = field.style or self.style story = [Paragraph(field.text, style)] story_inframe = KeepInFrame(field.width, field.height, story) frame.addFromList([story_inframe], canvas) canvas.save() packet.seek(0) new_pdf = PdfFileReader(packet) existing_page.mergePage(new_pdf.getPage(0)) output.addPage(existing_page) # write the final pdf to the file if isinstance(outputFile, basestring): outputFile = open(outputFile, "wb") output.write(outputFile) outputFile.close() else: output.write(outputFile)
def _header_footer(canvas, doc): # Save the state of our canvas so we can draw on it canvas.saveState() # canvas.setTitle("Shift export") styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='NormalText', fontName='OpenSans-Regular', fontSize=10)) styles.add( ParagraphStyle(name='BottomText', fontName='OpenSans-Regular', fontSize=8)) styles.add( ParagraphStyle(name='Schluessel', alignment=TA_CENTER, fontName='OpenSans-Regular', fontSize=14)) styles.add( ParagraphStyle(name='centered', alignment=TA_CENTER, fontName='OpenSans-Regular')) # Text that is found on the bottom of (right now..) every page! canvas.setFillColor(colors.lightgrey) canvas.rect(200, doc.bottomMargin, 125, 40, fill=True) frame1 = Frame(200, doc.bottomMargin, 125, 40, showBoundary=1, topPadding=10) story = [Paragraph('Schlüssel', styles['Schluessel'])] story_inframe = KeepInFrame(4 * inch, 8 * inch, story) frame1.addFromList([story_inframe], canvas) key_text = Paragraph("K Krank<br /><br />U Urlaub", styles['NormalText']) w, h = key_text.wrap(doc.width, doc.bottomMargin) key_text.drawOn(canvas, 200 + 125 + 5, doc.bottomMargin + 2.5) note_text = Paragraph( '* Tragen Sie in diese Spalte eines der folgenden Kürzel ein, ' 'wenn es für diesen Kalendertag zutrifft', styles['BottomText']) w, h = note_text.wrap(doc.width, doc.bottomMargin) note_text.drawOn(canvas, doc.leftMargin + 5, doc.bottomMargin + 45) status_text = Paragraph("Stand: 10/2015", styles['BottomText']) w, h = status_text.wrap(doc.width, doc.bottomMargin) status_text.drawOn(canvas, doc.width - 5 * mm, doc.bottomMargin) # Release the canvas canvas.restoreState()
def process_fields(data, canvas, fields, pagesize, options): # tl = top left; br = bottom right default_style = options.get('default', ParagraphStyle( name='default-default', fontSize=14, fontName='Helvetica', alignment=TA_CENTER, )) for fieldname, (bbox_tl, bbox_br) in fields.items(): style = options.get(fieldname, default_style) p = Paragraph(data.get(fieldname) or '',style) width = bbox_br[0] - bbox_tl[0] height = bbox_br[1] - bbox_tl[1] k = KeepInFrame(width*mm, height*mm, [p], mode='shrink') w,h = k.wrapOn(canvas, bbox_tl[1]*mm, bbox_tl[0]*mm ) vpos = pagesize[1] - bbox_tl[1]*mm - h # Adjust vpos: we want vertical alignment vpos -= (height*mm - h)/2.0 k.drawOn(canvas, bbox_tl[0]*mm, vpos) canvas.showPage()
def populate_pdf_form(template_file, message_class): """ Read in a PDF with form fields and apply the string contents of the messageDict dictionary to the cooresponding form fields. """ template = PdfReader(template_file) data = io.BytesIO() pdf = canvas.Canvas(data) for page in template.Root.Pages.Kids: for field in page.Annots: label = field.T key = message_class.data_map.get(label[1:-1], '') if 'value' in key: value = str(key.get('value', 'Test')) else: value = "TEST" if 'padding_top' in key: padding_top = key.get('padding_top', '') else: padding_top = message_class.defaults.get('padding_top', '') styles = message_class.styles box_sides = box_sides_in(field.Rect) left = min(box_sides[0], box_sides[2]) bottom = min(box_sides[1], box_sides[3]) width = box_sides[2] - box_sides[0] height = box_sides[3] - box_sides[1] form_field = Frame(left, bottom, width, height, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=padding_top, showBoundary=0) story = [Paragraph(value, styles['default'])] story_inframe = KeepInFrame(width, height, story) form_field.addFromList([story_inframe], pdf) pdf.showPage() pdf.save() data.seek(0) return data
def getPDF(): url = request.args.get("url") description = request.args.get("desc") image = ImageReader(url) c = canvas.Canvas('data/output.pdf', pagesize=letter) c.drawImage(image, 100, 325, width=400, height=400, mask='auto') frame1 = Frame(0.25 * inch, 0.25 * inch, 8 * inch, 4 * inch, showBoundary=1) styles = getSampleStyleSheet() para = [Paragraph("Description: " + description, styles['Normal'])] para_inframe = KeepInFrame(8 * inch, 8 * inch, para) frame1.addFromList([para_inframe], c) c.save() return send_from_directory('data', "output.pdf")
def writepdf(text, p, canvas): try: frmts = eval(text[4]) except (IndexError, SyntaxError): if text[4]: raise Exception('Error %s' % text[4]) else: frmts = [[]] for _ in range(int(text[3])): for frmt in frmts: styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.spaceBefore = 10 styleN.spaceAfter = 10 styleH = styles['Heading1'] title = Paragraph(text[0].format(*frmt), styleH) story = [] story.append(Paragraph(prep(text[1]).format(*frmt), styleN)) if text[2]: story.append( Paragraph('<br/>____________________________<br/>', styleN)) story.append( Paragraph('<br/>' + prep(text[2]).format(*frmt), styleN)) canvas.saveState() f = Frame(spacer + p[0] * width, spacer + p[1] * height, width, height, showBoundary=1) f.addFromList([title, KeepInFrame(height, width, story)], canvas) canvas.restoreState() if p == (2, 2): canvas.showPage() p = (0, 0) else: if p[1] == 2: p = (p[0] + 1, 0) else: p = (p[0], p[1] + 1) return p
def _draw_address(self, field): """ Draw address fields on certificate Using Frames to auto-adjust size/wrapping to fit designated area """ x, y = self.COORDINATES[field] address_content = self._paragraph_address(field) address_frame = Frame( x, y, self.ADDRESS_FRAME_WIDTH, self.ADDRESS_FRAME_HEIGHT, showBoundary=self.SHOW_BOUNDARY, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, ) inframe = KeepInFrame(content=address_content, maxWidth=self.ADDRESS_FRAME_WIDTH, maxHeight=self.ADDRESS_FRAME_HEIGHT) address_frame.addFromList([inframe], self.canvas)
def draw(self): self.canv.saveState() data_text = None if self.text: data_text = self.text if data_text: data_frame = Frame(self.x, self.y, self.width, self.height, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) data_inframe = KeepInFrame( self.width, self.height, data_text, vAlign='TOP', fakeWidth=False, ) data_frame.addFromList([data_inframe], self.canv) self.canv.restoreState()
width = 430 height = 60 # SETS THE FILL COLOR AND CREATES THE INNER RECTANGLE FOR THE TITLE c.setFillColorRGB(178 / 255, 34 / 255, 52 / 255) c.rect(cx, cy, width, height, fill=1) # CREATES THE TITLE s = "DEBATE BINGO" frame1 = Frame(cx, cy, width, height, showBoundary=0) style = ParagraphStyle(name='Normal', fontSize=45, alignment=1, textColor='White') story = [Paragraph(s, style)] story_inframe = KeepInFrame(width, height, story) frame1.addFromList([story_inframe], c) # CREATES A LIST OF FRAMES FOR EACH INDIVIDUAL GRID ELEMENT gridFramesList = [] frameWidth = 90 frameHeight = 80 for i in range(5): for j in range(5): gFrame = Frame(xl[i], yl[j] - frameHeight, frameWidth, frameHeight, showBoundary=0) gridFramesList.append(gFrame)
class Div(Flowable): def __init__(self, story, height=None, width=None, pos_x=None, pos_y=None, frame_attrs=freeze({}), attributes=freeze({}), pto_trailer=None, pto_header=None): Flowable.__init__(self) # get on story self.div_story = story # set frame style self.frame_attrs = {'leftPadding': 0, 'bottomPadding': 0, 'rightPadding': 0, 'topPadding': 0, 'showBoundary': 0} # PTO initialisation self.pto_trailer = pto_trailer self.pto_header = pto_header if frame_attrs is not None: self.frame_attrs.update(frame_attrs) for margin in ('topMargin', 'bottomMargin', 'leftMargin', 'rightMargin'): if margin in self.frame_attrs: del self.frame_attrs[margin] border = self.frame_attrs['showBoundary'] if isinstance(border, ShowBoundaryValue): border = border.width if border: for padding_attr in FRAME_PADDINGS_KEYS: self.frame_attrs[padding_attr] += border self.frame_width = width # Overflow # TODO to improve self.keep_in_frame = None style = attribute_style_to_dict(attributes.get((None, 'style'), '')) self.overflow = style.get('overflow-y', None) if self.overflow == 'hidden': self.overflow = 'truncate' else: self.overflow = None def draw(self): # set position for the frame self.pos_x, self.pos_y = self._get_current_position(self.canv) # XXX This is false, height=drawHeigh and drawHeight should take into # account the frame padding height = (self.drawHeight + self.frame_attrs['leftPadding'] + self.frame_attrs['rightPadding']) width = (self.drawWidth + self.frame_attrs['topPadding'] + self.frame_attrs['bottomPadding']) self.frame = Frame(self.pos_x, self.pos_y, width, height, **self.frame_attrs) if self.overflow: # Hack, We lie by setting the new created frame as default frame # of the doc template # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" _doctemplate = self.canv._doctemplate # save state current_frame = getattr(_doctemplate, 'frame', None) _doctemplate.frame = self.frame # Check if PTO is defined if self.pto_trailer or self.pto_header: ptocontainer = PTOContainer(self.div_story[:], self.pto_trailer, self.pto_header) ptocontainer.canv = self.canv pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight) # XXX Round the height to avoid problems with decimal if int(pto_size[1]) > int(self.drawHeight): pto_story = ptocontainer.split(self.drawWidth, self.drawHeight) self.frame.addFromList(pto_story, self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) # restore state if current_frame: _doctemplate.frame = current_frame else: self.frame.addFromList(self.div_story[:], self.canv) def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height(availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight def getSpaceBefore(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceBefore() # XXX default value return 0 def getSpaceAfter(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceAfter() # XXX default value return 0 def _get_real_size(self, availWidth, availHeight=10000000): """By default we use a fake height to calculate the real height of the flowables""" self.drawWidth = self.width or availWidth self.drawWidth -= self.frame_attrs['leftPadding'] self.drawWidth -= self.frame_attrs['rightPadding'] self.drawHeight = 0 at_top = True for element in self.div_story[:]: if at_top: at_top = False else: self.drawHeight += element.getSpaceBefore() flowHeight = element.wrap(availWidth, availHeight-self.drawHeight)[1] self.drawHeight += flowHeight self.drawHeight += element.getSpaceAfter() self.drawHeight += self.frame_attrs['topPadding'] self.drawHeight += self.frame_attrs['bottomPadding'] return (self.drawWidth, self.drawHeight) def _align_frame(self, available_width, hAlign): if hAlign == 'CENTER': self.pox_x = (available_width - self.frame_width) / 2 + self.pos_x elif hAlign == 'RIGHT': self.pos_x = available_width - self.frame_width + self.pox_x def _get_current_position(self, canv): return (canv._x, canv._y) def _get_current_absolute_position(self, canv): return canv.absolutePosition(canv._x, canv._y) def _get_main_frame_height(self, default, ratio=0.9): if self.canv is None: return default value = self.canv._doctemplate.main_frame_attr.get('height', default) return value * ratio
def later_pages(canvas, document): canvas.saveState() # Заключительные диагнозы # Основной заключительный диагноз final_diagnos_text = [ Paragraph('{}'.format(final_diagnos), styleJustified) ] final_diagnos_frame = Frame(27 * mm, 230 * mm, 175 * mm, 45 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) final_diagnos_inframe = KeepInFrame( 175 * mm, 50 * mm, final_diagnos_text, hAlign='LEFT', vAlign='TOP', ) final_diagnos_frame.addFromList([final_diagnos_inframe], canvas) # Осложнения основного заключительного диагноза other_diagnos_text = [ Paragraph('{}'.format(other_diagnos), styleJustified) ] other_diagnos_frame = Frame(27 * mm, 205 * mm, 175 * mm, 20 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) other_diagnos_inframe = KeepInFrame( 175 * mm, 20 * mm, other_diagnos_text, hAlign='LEFT', vAlign='TOP', ) other_diagnos_frame.addFromList([other_diagnos_inframe], canvas) # Сопутствующие основного заключительного диагноза near_diagnos_text = [ Paragraph( '{}'.format( near_diagnos.replace('<', '<').replace('>', '>')), styleJustified) ] near_diagnos_frame = Frame(27 * mm, 181 * mm, 175 * mm, 20 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) near_diagnos_inframe = KeepInFrame( 175 * mm, 20 * mm, near_diagnos_text, vAlign='TOP', ) near_diagnos_frame.addFromList([near_diagnos_inframe], canvas) # Таблица операции operation_text = [tbl_o] operation_frame = Frame(22 * mm, 123 * mm, 170 * mm, 40 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=0) operation_inframe = KeepInFrame(175 * mm, 40 * mm, operation_text, hAlign='CENTRE', vAlign='TOP', fakeWidth=False) operation_frame.addFromList([operation_inframe], canvas) canvas.setFont('PTAstraSerifBold', 8) hospital: Hospitals = request_data["hospital"] hospital_name = hospital.safe_short_title canvas.drawString(55 * mm, 12 * mm, '{}'.format(hospital_name)) canvas.drawString( 55 * mm, 9 * mm, '№ карты : {}; Номер истории: {}'.format(p_card_num, hosp_nums)) canvas.drawString( 55 * mm, 6 * mm, 'Пациент: {} {}'.format(patient_data['fio'], patient_data['born'])) canvas.line(55 * mm, 11.5 * mm, 200 * mm, 11.5 * mm) canvas.restoreState()
def generateFicheTheme(pdf_filename, vars, size=(325.984, 240.945)): sizeX = size[0] sizeY = size[1] midX = size[0] / 2 midY = size[1] / 2 marginX = 10 marginY = 10 cnv = canvas.Canvas(pdf_filename, pagesize=size, verbosity=1) # 115 x 85 mm style_eco = ParagraphStyle(name='ObsEco', fontSize=10, leading=10, fontName='Helvetica-Oblique') style_notes = ParagraphStyle(name='ObsNotes', fontSize=9, leading=9, fontName='Helvetica-Bold') style_titre = ParagraphStyle(name='ThemeTitre', fontName='Helvetica-Bold', fontSize=14, alignment=1, textColor=colors.Color( 239 / 255, 239 / 255, 0, 1)) style_nomenc = ParagraphStyle(name='Nomenc', fontName='Helvetica-BoldOblique', fontSize=12) style_nomenc_bis = ParagraphStyle(name='Nomenc', fontName='Helvetica-Oblique', fontSize=10) style_noms = ParagraphStyle(name='Noms', fontSize=16, alignment=1, fontName='Helvetica-Bold', leading=16) # Rectangle du haut cnv.setStrokeColorRGB(80 / 255, 80 / 255, 80 / 255) cnv.setLineWidth(2) cnv.setFillColorRGB(80 / 255, 80 / 255, 80 / 255) cnv.rect(0, sizeY - (10 * mm), sizeX, 10 * mm, fill=True) # Bordure pour le massicot cnv.setStrokeColorRGB(0, 0, 0) cnv.setLineWidth(1) cnv.rect(0, 0, sizeX, sizeY, stroke=1, fill=0) # Numero de fiche cnv.setStrokeColorRGB(0, 0, 0) cnv.setFillColorRGB(1, 1, 1) cnv.drawRightString(sizeX - marginX, sizeY - (marginY + 10), vars['fiche']) # Theme cnv.drawString(marginX, sizeY - (marginY + 10), vars['theme_code']) cnv.setFillColorRGB(0, 0, 0) frameW = sizeX - (9 * marginX) frameH = marginY * 2.5 frame_titre = Frame(4.5 * marginX, sizeY - marginY * 2.7, frameW, frameH, showBoundary=0, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) titre = [Paragraph(vars['theme_titre'], style_titre)] titre_inframe = KeepInFrame(frameW, frameH, titre) frame_titre.addFromList([titre_inframe], cnv) # Genre et Espece cnv.setFillColorRGB(0, 0, 0) frameW = 0.9 * sizeX frameH = 3 * marginY frame_nomenc = Frame(marginX * 0.6, sizeY - (10 * mm) - frameH, frameW, frameH, showBoundary=0, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) nomenc = [] # Genre et Espece genre_esp = vars['genre'] + ' ' + vars['espece'] if vars['variete'] != "": genre_esp += ' var. ' + vars['variete'] elif vars['forme'] != "": genre_esp += ' f. ' + vars['forme'] nomenc.append(Paragraph(genre_esp, style_nomenc)) if 'usuel_genre' in vars.keys(): nomenc.append( Paragraph( '( = ' + vars['usuel_genre'] + ' ' + vars['usuel_espece'] + ' ) ', style_nomenc_bis)) if vars['usuel_variete'] != "": nomenc.append( Paragraph('var. ' + vars['usuel_variete'], style_nomenc_bis)) elif vars['usuel_forme'] != "": nomenc.append( Paragraph('f. ' + vars['usuel_forme'], style_nomenc_bis)) nomenc_inframe = KeepInFrame(frameW, frameH, nomenc) frame_nomenc.addFromList([nomenc_inframe], cnv) cnv.setFont('Helvetica', 11) # Noms usuels if 'noms' in vars.keys() and vars['noms'] != "": frameW = sizeX * 0.75 frameH = marginY * 6 frame_noms = Frame(marginX, midY - 3 * marginY, frameW, frameH, showBoundary=0, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) noms = [] for nom in vars['noms'].splitlines(): if nom != "": noms.append(Paragraph(nom, style_noms)) noms_inframe = KeepInFrame(frameW, frameH, noms) frame_noms.addFromList([noms_inframe], cnv) # Texte comestibilite if 'comestibilite' in vars.keys() and vars['comestibilite'] != "": assets_path = settings.BASE_DIR + '/app/pdf_assets/' if (vars['comestibilite'] == 'C'): com_txt = 'Comestible' com_img = assets_path + 'Comest.bmp' elif (vars['comestibilite'] == 'NC'): com_txt = 'Non Comestible' com_img = assets_path + 'NonCom.bmp' elif (vars['comestibilite'] == 'T'): com_txt = 'Toxique' com_img = assets_path + 'Toxique.bmp' else: com_txt = 'Mortel' com_img = assets_path + 'Mortel.bmp' img_width = 138.75 / 2.5 img_height = 131.25 / 2.5 cnv.drawImage(com_img, sizeX - marginX - img_width, midY + (0.5 * marginY), width=img_width, height=img_width) cnv.drawRightString(sizeX - marginX, midY - (0 * marginY) - 5, com_txt) # Rectangle du bas cnv.setLineWidth(1) frame_obs = Frame(0 + marginX, 5 + marginY, sizeX - (2 * marginX), sizeY / 6, showBoundary=1, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) # Observations if 'obs' in vars.keys(): notes = [Paragraph(vars['obs'][0], style_notes)] eco = [Paragraph(vars['obs'][1], style_eco)] frame_eco = Frame(0 + marginX, 5 + (1 * marginY) + sizeY / 6, sizeX - (2 * marginX), 2.6 * marginY, showBoundary=0, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) notes_inframe = KeepInFrame(sizeX - (2 * marginX), sizeY / 6, notes) eco_inframe = KeepInFrame(sizeX - (2 * marginX), 2.6 * marginY, eco) frame_obs.addFromList([notes_inframe], cnv) frame_eco.addFromList([eco_inframe], cnv) # Copyright cnv.setFont('Helvetica', 8) year = str(datetime.datetime.now().year) cnv.drawRightString(sizeX - marginX, marginY - 5, '©SMS ' + year) # Code Barre (standard code39) barcode = code39.Standard39(vars['taxon'], barWidth=0.5 * mm, barHeight=3.5 * mm, checksum=0) barcode.drawOn(cnv, 10, 3) cnv.showPage() cnv.save()
def generateFiche(pdf_filename, vars, size=(115 * mm, 85 * mm)): sizeX = size[0] sizeY = size[1] midX = size[0] / 2 midY = size[1] / 2 marginX = 10 marginY = 10 cnv = canvas.Canvas(pdf_filename, pagesize=size, verbosity=1) # 115 x 85 mm # Bordure pour le massicot cnv.rect(0, 0, sizeX, sizeY, stroke=1, fill=0) # Styles pour les paragraphes styleSheet = getSampleStyleSheet() style = styleSheet['BodyText'] style_obs = ParagraphStyle(name='Obs', fontSize=9, leading=9, fontName='Helvetica-Oblique') style_usuel = ParagraphStyle(name='SynoUsuel', fontSize=12, alignment=1, leading=12) # Genre - Espece style_nomenc = ParagraphStyle(name='Nomenclature', fontSize=18, alignment=1, fontName='Helvetica-Bold', leading=22) # Variete - Forme style_nomenc_bis = ParagraphStyle(name='NomenclatureBis', fontSize=14, alignment=1, leading=11, fontName='Helvetica-Bold') # Noms style_noms = ParagraphStyle(name='Noms', fontSize=12, leading=12, fontName='Helvetica-Bold') # Theme if 'theme' in vars.keys(): cnv.drawString(marginX, sizeY - (marginY + 10), vars['theme']) # Numero de fiche cnv.drawRightString(sizeX - marginX, sizeY - (marginY + 10), vars['fiche']) # Rectangle supérieur cnv.setLineWidth(2) frame_top = Frame(0 + marginX, midY + (4.5 * marginY) + 5, sizeX - (2 * marginX), sizeY / 5, showBoundary=1, topPadding=2, leftPadding=2, rightPadding=2, bottomPadding=2) nomenc = [] # Genre et Espece nomenc.append(Paragraph(vars['genre'] + ' ' + vars['espece'], style_nomenc)) # Variete et Forme if vars['variete'] != "": nomenc.append(Paragraph('var. ' + vars['variete'], style_nomenc_bis)) elif vars['forme'] != "": nomenc.append(Paragraph('f. ' + vars['forme'], style_nomenc_bis)) nomenc_inframe = KeepInFrame(sizeX - (2 * marginX), sizeY / 5, nomenc) frame_top.addFromList([nomenc_inframe], cnv) cnv.setLineWidth(1) # Noms if 'noms' in vars.keys() and vars['noms'] != "": frameW = sizeX * 0.65 frameH = marginY * 7 frame_noms = Frame(marginX, midY - 4.5 * marginY, frameW, frameH, showBoundary=0) noms = [] for nom in vars['noms'].splitlines(): if nom != "": noms.append(Paragraph(nom, style_noms)) noms_inframe = KeepInFrame(frameW, frameH, noms) frame_noms.addFromList([noms_inframe], cnv) # Synonyme usuel if 'usuel_genre' in vars.keys(): frameW = 0.66 * sizeX frameH = marginY * 3.5 frame_syno = Frame(0.165 * sizeX, midY + 2 * marginY, frameW, frameH, showBoundary=0) if vars['usuel_variete'] != "": varfor_str = ' var. ' + vars['usuel_variete'] elif vars['usuel_forme'] != "": varfor_str = ' f. ' + vars['usuel_forme'] else: varfor_str = '' ustr = '( = ' + vars['usuel_genre'] + ' ' + vars[ 'usuel_espece'] + varfor_str + ' )' usuel = [Paragraph(ustr, style_usuel)] usuel_inframe = KeepInFrame(frameW, frameH, usuel) frame_syno.addFromList([usuel_inframe], cnv) # Texte comestibilite if 'comestibilite' in vars.keys() and vars['comestibilite'] != "": assets_path = settings.BASE_DIR + '/app/pdf_assets/' if (vars['comestibilite'] == 'C'): com_txt = 'Comestible' com_img = assets_path + 'Comest.bmp' elif (vars['comestibilite'] == 'NC'): com_txt = 'Non Comestible' com_img = assets_path + 'NonCom.bmp' elif (vars['comestibilite'] == 'T'): com_txt = 'Toxique' com_img = assets_path + 'Toxique.bmp' else: com_txt = 'Mortel' com_img = assets_path + 'Mortel.bmp' img_width = 138.75 / 2.5 img_height = 131.25 / 2.5 cnv.drawImage(com_img, sizeX - marginX - img_width, midY - (1.5 * marginY), width=img_width, height=img_width) cnv.drawRightString(sizeX - marginX, midY - (2 * marginY) - 5, com_txt) # Rectangle du bas cnv.setLineWidth(1) frameW = sizeX - (2 * marginX) frameH = sizeY / 5 frame_obs = Frame(0 + marginX, 5 + marginY, frameW, frameH, showBoundary=1, leftPadding=2, topPadding=2, rightPadding=2, bottomPadding=2) # Observations if 'obs' in vars.keys(): observations = [ Paragraph(vars['obs'][0], style_obs), Paragraph(vars['obs'][1], style_obs) ] obs_inframe = KeepInFrame(frameW, frameH, observations) frame_obs.addFromList([obs_inframe], cnv) # Copyright cnv.setFont('Helvetica', 8) year = str(datetime.datetime.now().year) cnv.drawRightString(sizeX - marginX, marginY - 5, '©SMS ' + year) # Code Barre (standard code39) barcode = code39.Standard39(vars['taxon'], barWidth=0.5 * mm, barHeight=3.5 * mm, checksum=0) barcode.drawOn(cnv, 10, 3) cnv.showPage() cnv.save()
def draw_text(report, text, attributes): """ Draw text string on report_info. :param report: :param text: text to output to report_info :param attributes: attributes (e.g. 'font name', 'font size', 'color') to apply to text """ report['canvas'].saveState() text = format_text(text, attributes) styles = getSampleStyleSheet() text_alignment = {'Left': TA_LEFT, 'Center': TA_CENTER, 'Right': TA_RIGHT, 'Justified': TA_JUSTIFY} base_style = styles['Normal'] left_indent = attributes.get("leftIndent", base_style.leftIndent) right_indent = attributes.get("rightIndent", base_style.leftIndent) font_name = get_font(report, attributes, base_style) font_is_bold = convert2boolean(attributes.get('fontIsBold')) if font_is_bold: text = '<b>' + text + '</b>' font_is_italic = convert2boolean(attributes.get('fontIsItalic')) if font_is_italic: text = '<i>' + text + '</i>' font_is_underline = convert2boolean(attributes.get('fontIsUnderline')) if font_is_underline: text = '<u>' + text + '</u>' font_is_strike_through = convert2boolean(attributes.get('fontIsStrikeThrough')) if font_is_strike_through: text = '<strike>' + text + '</strike>' font_size = attributes.get('fontSize', 10) text_color = attributes.get('forecolor') if text_color is None: text_color = base_style.textColor else: text_color = colors.HexColor(text_color) ps = ParagraphStyle(name='cell', parent=styles['Normal'], fontName=font_name, fontSize=font_size, leading=font_size * 1.2, leftIndent=left_indent, rightIndent=right_indent, alignment=text_alignment[attributes.get('textAlignment', 'Left')], textColor=text_color ) # text = "<br/>".join(str(text).split('\n')) # replace '\n' with a <br/> to cause newline text = str(text).replace('\n', '<br/>') # story = [Paragraph(str(text), ps)] story = [Paragraph(text, ps)] story_in_frame = KeepInFrame(attributes['width'], attributes['height'], story, mode='shrink') # 'truncate, overflow, shrink data = [[story_in_frame]] t = Table(data, colWidths=attributes['width'], rowHeights=attributes['height']) table_style = TableStyle([ ('VALIGN', (0,0),(0,0), attributes.get('verticalAlignment', 'TOP').upper()), ('TEXTCOLOR', (0, 0), (0, 0), colors.black), ('LEFTPADDING', (0, 0), (0, 0), 0), ('RIGHTPADDING', (0, 0), (0, 0), 0), ('TOPPADDING', (0, 0), (0, 0), 0), ('BOTTOMPADDING', (0, 0), (0, 0), 0), ]) if attributes.get('mode') is not None: backcolor = attributes.get('backcolor') if backcolor is not None: table_style.add('BACKGROUND', (0, 0), (0, 0), colors.HexColor(backcolor)) t.setStyle(table_style) t.wrapOn(report['canvas'], attributes['width'], attributes['height']) t.drawOn(report['canvas'], attributes['x'], report['cur_y'] - attributes['y'] - attributes['height']) report['canvas'].restoreState()
class Div(Flowable): def __init__(self, story, height=None, width=None, pos_x=None, pos_y=None, frame_attrs=freeze({}), attributes=freeze({}), pto_trailer=None, pto_header=None): Flowable.__init__(self) # get on story self.div_story = story # set frame style self.frame_attrs = { 'leftPadding': 0, 'bottomPadding': 0, 'rightPadding': 0, 'topPadding': 0, 'showBoundary': 0 } # PTO initialisation self.pto_trailer = pto_trailer self.pto_header = pto_header if frame_attrs is not None: self.frame_attrs.update(frame_attrs) for margin in ('topMargin', 'bottomMargin', 'leftMargin', 'rightMargin'): if margin in self.frame_attrs: del self.frame_attrs[margin] border = self.frame_attrs['showBoundary'] if isinstance(border, ShowBoundaryValue): border = border.width if border: for padding_attr in FRAME_PADDINGS_KEYS: self.frame_attrs[padding_attr] += border self.frame_width = width # Overflow # TODO to improve self.keep_in_frame = None style = attribute_style_to_dict(attributes.get((None, 'style'), '')) self.overflow = style.get('overflow-y', None) if self.overflow == 'hidden': self.overflow = 'truncate' else: self.overflow = None def draw(self): # set position for the frame self.pos_x, self.pos_y = self._get_current_position(self.canv) # XXX This is false, height=drawHeigh and drawHeight should take into # account the frame padding height = (self.drawHeight + self.frame_attrs['leftPadding'] + self.frame_attrs['rightPadding']) width = (self.drawWidth + self.frame_attrs['topPadding'] + self.frame_attrs['bottomPadding']) self.frame = Frame(self.pos_x, self.pos_y, width, height, **self.frame_attrs) if self.overflow: # Hack, We lie by setting the new created frame as default frame # of the doc template # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" _doctemplate = self.canv._doctemplate # save state current_frame = getattr(_doctemplate, 'frame', None) _doctemplate.frame = self.frame # Check if PTO is defined if self.pto_trailer or self.pto_header: ptocontainer = PTOContainer(self.div_story[:], self.pto_trailer, self.pto_header) ptocontainer.canv = self.canv pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight) # XXX Round the height to avoid problems with decimal if int(pto_size[1]) > int(self.drawHeight): pto_story = ptocontainer.split(self.drawWidth, self.drawHeight) self.frame.addFromList(pto_story, self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) # restore state if current_frame: _doctemplate.frame = current_frame else: self.frame.addFromList(self.div_story[:], self.canv) def wrap(self, availWidth, availHeight): canv = self.canv if self.overflow: if self.keep_in_frame is None: # FIXME if the availHeight is very small # We consider that there is no enough space # and we calculate the real size of the flowables if availHeight <= 0: width, height = self._get_real_size(availWidth) else: width, height = availWidth, availHeight # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) self.keep_in_frame = KeepInFrame(width, height, self.div_story[:], mode=self.overflow) else: width, height = availWidth, availHeight # FIXME Usefull ? # Dirty hack, get the current frame height and use it # if height is too small main_frame_height = self._get_main_frame_height( availHeight, 0.8) if height == -1e-06: height = main_frame_height else: height = min(height, main_frame_height) # Set the canva self.keep_in_frame.canv = canv # Hack, We remove the attribute _doctemplate of the canv # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" if hasattr(canv, '_doctemplate'): _doctemplate = canv._doctemplate # Remove _doctemplate canv._doctemplate = None w, h = self.keep_in_frame.wrap(width, height) if hasattr(canv, '_doctemplate'): # Restore _doctemplate canv._doctemplate = _doctemplate self.drawWidth, self.drawHeight = w, h else: width, height = self._get_real_size(availWidth) self.drawWidth, self.drawHeight = width, height return self.drawWidth, self.drawHeight def getSpaceBefore(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceBefore() # XXX default value return 0 def getSpaceAfter(self): if self.overflow and self.keep_in_frame: return self.keep_in_frame.getSpaceAfter() # XXX default value return 0 def _get_real_size(self, availWidth, availHeight=10000000): """By default we use a fake height to calculate the real height of the flowables""" self.drawWidth = self.width or availWidth self.drawWidth -= self.frame_attrs['leftPadding'] self.drawWidth -= self.frame_attrs['rightPadding'] self.drawHeight = 0 at_top = True for element in self.div_story[:]: if at_top: at_top = False else: self.drawHeight += element.getSpaceBefore() flowHeight = element.wrap(availWidth, availHeight - self.drawHeight)[1] self.drawHeight += flowHeight self.drawHeight += element.getSpaceAfter() self.drawHeight += self.frame_attrs['topPadding'] self.drawHeight += self.frame_attrs['bottomPadding'] return (self.drawWidth, self.drawHeight) def _align_frame(self, available_width, hAlign): if hAlign == 'CENTER': self.pox_x = (available_width - self.frame_width) / 2 + self.pos_x elif hAlign == 'RIGHT': self.pos_x = available_width - self.frame_width + self.pox_x def _get_current_position(self, canv): return (canv._x, canv._y) def _get_current_absolute_position(self, canv): return canv.absolutePosition(canv._x, canv._y) def _get_main_frame_height(self, default, ratio=0.9): if self.canv is None: return default value = self.canv._doctemplate.main_frame_attr.get('height', default) return value * ratio
def keep_in_frame(self, widget, width, height, paragraphs, mode): widget.keep = KeepInFrame(width, height, paragraphs, mode=mode) widget.keep.canv = self.canvas widget.keep.wrap(self.calculate_size(widget.width), self.calculate_size(widget.height))
canvas.restoreState() #first page template doc.addPageTemplates([repo_page_template()]) #debug piece P0 = Paragraph( ''' <b>A pa<font color=red>r</font>a<i>graph</i></b> <super><font color=yellow>1</font></super>''', styles["BodyText"]) P = KeepInFrame(20 * xc / 5, 9 * yc / 10, [ Paragraph( ''' <para align=center spaceb=3>The <b>ReportLab Left <font color=red>Logo</font></b> Image</para>''', styles["BodyText"]) ]) I = Image('.\\logo.jpg') I.drawWidth = (7 * yc / 10) * I.drawWidth / I.drawHeight I.drawHeight = 7 * yc / 10 data = [['A', 'B', 'C', P0, 'D'], ['00', '01', '02', [I, P], '04'], ['10', '11', '12', [P, I], '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']] Tstyle = [ ('GRID', (1, 1), (-2, -2), 1, colors.green), ('BOX', (0, 0), (1, -1), 2, colors.red), ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue), ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
def printForm(): hospital_name = dir.hospital_short_title hospital_address = SettingManager.get("org_address") hospital_kod_ogrn = SettingManager.get("org_ogrn") if sys.platform == 'win32': locale.setlocale(locale.LC_ALL, 'rus_rus') else: locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') pdfmetrics.registerFont( TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf'))) pdfmetrics.registerFont( TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf'))) styleSheet = getSampleStyleSheet() style = styleSheet["Normal"] style.fontName = "PTAstraSerifReg" style.fontSize = 10.5 style.leading = 14 style.spaceAfter = 1 * mm styleCenterBold = deepcopy(style) styleCenterBold.alignment = TA_CENTER styleCenterBold.fontSize = 12 styleCenterBold.leading = 15 styleCenterBold.fontName = 'PTAstraSerifBold' styleT = deepcopy(style) styleT.alignment = TA_LEFT styleT.fontSize = 10 styleT.leading = 4.5 * mm styleT.face = 'PTAstraSerifReg' barcode = eanbc.Ean13BarcodeWidget(dir.pk + 460000000000, humanReadable=0, barHeight=8 * mm, barWidth=1.25) dir_code = Drawing() dir_code.add(barcode) renderPDF.draw(dir_code, c, 157 * mm, 259 * mm) objs = [] if dir.hospital: source_hospital = dir.hospital hospital_name = source_hospital.safe_short_title hospital_address = source_hospital.safe_address hospital_kod_ogrn = source_hospital.safe_ogrn opinion = [ [ Paragraph( f'<font size=11>{hospital_name}<br/>Адрес: {hospital_address}<br/>ОГРН: {hospital_kod_ogrn} <br/> </font>', styleT), Paragraph( '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: <br/>' 'Медицинская документация<br/>Учетная форма № 014/у</font>', styleT), ], ] tbl = Table(opinion, 2 * [100 * mm]) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 55 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(tbl) objs.append(Spacer(1, 5 * mm)) history_num = '' try: issledovaniye = Issledovaniya.objects.get(napravleniye=dir.pk) except ObjectDoesNotExist: issledovaniye = None short_title = issledovaniye.research.short_title if dir.parent and dir.parent.research.is_hospital: history_num = f"(cтационар-{str(dir.parent.napravleniye_id)})" objs.append( Paragraph(f'НАПРАВЛЕНИЕ № {dir.pk} {history_num} ', styleCenterBold)) objs.append( Paragraph( 'НА ПРИЖИЗНЕННОЕ ПАТОЛОГО-АНАТОМИЧЕСКОЕ<br/> ИССЛЕДОВАНИЕ БИОПСИЙНОГО (ОПЕРАЦИОННОГО) МАТЕРИАЛА', styleCenterBold)) objs.append(Paragraph(f'{short_title.upper()}', styleCenterBold)) objs.append(Spacer(1, 10 * mm)) space_symbol = ' ' direction_params = DirectionParamsResult.objects.filter( napravleniye=dir) descriptive_values = [] patient_locality = "" laboratory_value, purpose, table_value, main_diagnos, mkb10_code, clinical_data, method_get_material, doc_get_material, previous_result = ( None, None, None, None, None, None, None, None, None, ) date_get_material = '_________________________' time_get_material = '______________' is_aqua_material = '(да/нет)___________' purpose = 'Уточнение диагноза' department = "" for param in direction_params: if param.field_type == 24: laboratory_value = param.value elif param.field_type == 27: table_value = param.value elif param.field_type in [26, 25]: descriptive_values.append(param.value) elif param.title == 'Цель': purpose = param.value elif param.title == 'Диагноз основной': main_diagnos = param.value elif param.title == 'результаты предыдущие': previous_result = param.value elif param.title.strip() == 'Код по МКБ': try: value = json.loads(param.value) mkb10_code = value["code"] except: mkb10_code = param.value elif param.title == 'Дополнительные клинические сведения': clinical_data = param.value elif param.title == 'Способ получения биопсийного (операционного) материала': method_get_material = param.value elif param.title == 'Материал помещен в 10%-ный раствор нейтрального формалина': is_aqua_material = param.value elif param.title == 'Дата забора материала': date_get_material = normalize_dash_date(param.value) elif param.title == 'Время забора материала': time_get_material = param.value elif param.title == 'ФИО врача': doc_get_material = param.value elif param.title == 'Вид места жительства': try: value = json.loads(param.value) patient_locality = f'{value.get("title", "")} -{value.get("code", "")}' except: patient_locality = "Городская -1, Сельская -2" elif param.title == 'Отделение': department = param.value if not dir.is_external: department = dir.get_doc_podrazdeleniye_title() objs.append( Paragraph( f'1. Отделение, направившее биопсийный (операционный) материал: {department}', style)) objs.append( Paragraph( f'2. Фамилия, имя, отчество (при наличии) пациента: {dir.client.individual.fio()}', style)) sex = dir.client.individual.sex if sex == "м": sex = f'{sex}-1' else: sex = f'{sex}-2' objs.append( Paragraph( f'3. Пол: {sex}, {space_symbol * 5} 4. Дата рождения: число: {dir.client.individual.bd()}', style)) polis_num = '' polis_issue = '' snils = '' ind_data = dir.client.get_data_individual() if ind_data['oms']['polis_num']: polis_num = ind_data['oms']['polis_num'] if ind_data['oms']['polis_issued']: polis_issue = ind_data['oms']['polis_issued'] objs.append( Paragraph(f'5. Полис ОМС: {polis_num} с/к: {polis_issue}', style)) if ind_data['snils']: snils = ind_data['snils'] objs.append(Paragraph(f'6. СНИЛС: {snils}', style)) address = ind_data['main_address'] objs.append(Paragraph(f'7. Место регистрации: {address}', style)) objs.append(Paragraph(f'8. Местность: {patient_locality}', style)) hosp_operation = None if dir.parent and len( hosp_get_operation_data(dir.parent.napravleniye_id)) > 0: hosp_operation = hosp_get_operation_data( dir.parent.napravleniye_id)[-1] diagnos_after_operation = '' mkb10 = '' if hosp_operation: diagnos_after_operation = hosp_operation['diagnos_after_operation'] mkb10 = hosp_operation['mkb10'] if main_diagnos: diagnos_after_operation = main_diagnos objs.append( Paragraph( f"9. Диагноз основного заболевания (состояния): <font face=\"PTAstraSerifBold\">{diagnos_after_operation}</font>", style)) objs.append( Paragraph( '_______________________________________________________________________________________________________', style)) diagnosis = '' if mkb10_code: mkb10 = mkb10_code if mkb10.strip(): diagnosis = mkb10.strip().split(' ')[0] elif dir.diagnos.strip(): diagnosis = dir.diagnos.strip() objs.append(Paragraph(f'10. Код по МКБ: {diagnosis}', style)) objs.append( Paragraph( '11. Задача прижизненного патолого-анатомического исследования биопсийного (операционного) материала', style)) objs.append(Paragraph(f'<u>{purpose}</u>', style)) objs.append( Paragraph( '12. Дополнительные клинические сведения (основные симптомы, оперативное или гормональное, или лучевое лечение,', style)) objs.append( Paragraph( 'результаты инструментальных и лабораторных исследований)__________________________________________________', style)) if clinical_data: objs.append(Paragraph(f"{clinical_data}", style)) if not laboratory_value: objs.append( Paragraph( '_______________________________________________________________________________________________________', style)) if laboratory_value: lab_values = previous_laboratory_result(laboratory_value) if lab_values: objs.extend(lab_values) if descriptive_values: for v in descriptive_values: objs = previous_doc_refferal_result(v, objs) objs.append( Paragraph( '13. Результаты предыдущих прижизненных патолого-анатомических исследований (наименование медицинской организа-ции, дата, регистрационный номер, заключение)', style)) if not previous_result: previous_result = '_______________________________________________________________________________________________________' objs.append(Paragraph(f'{previous_result}', style)) objs.append( Paragraph( '14. Проведенное предоперационное лечение (вид лечения, его сроки, дозировка лекарственного препарата, доза облучения)', style)) objs.append( Paragraph( '_______________________________________________________________________________________________________', style)) objs.append( Paragraph( '_______________________________________________________________________________________________________', style)) if not method_get_material: objs.append( Paragraph( '15. Способ получения биопсийного (операционного) материала: эндоскопическая биопсия—1, пункционная биопсия—2,', style)) objs.append( Paragraph( 'аспирационная биопсия—3, инцизионная биопсия—4, операционная биопсия—5, операционный материал—6,', style)) objs.append( Paragraph('самопроизвольно отделившиеся фрагменты тканей—7.', style)) else: objs.append( Paragraph( f'15. Способ получения биопсийного (операционного) материала: {method_get_material}', style)) objs.append( Paragraph( f'16. Дата забора материала {date_get_material} время {time_get_material}', style)) objs.append( Paragraph( f'17. Материал помещен в 10%-ный раствор нейтрального формалина {is_aqua_material}', style)) objs.append( Paragraph( '18. Маркировка биопсийного (операционного) материала (расшифровка маркировки флаконов):', style)) if not table_value: opinion = [ [ Paragraph('Номер флакона', styleT), Paragraph( 'Локализация патологического процесса (орган, топография)', styleT), Paragraph( 'Характер патологического процесса (эрозия, язва, полип, пятно, узел, внешне не измененная ткань, отношение к окружающим тканям)', styleT), Paragraph('Количество объектов', styleT), ], [ Paragraph('1', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT) ], [ Paragraph('2', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT) ], [ Paragraph('3', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT) ], [ Paragraph('4', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT) ], [ Paragraph('5', styleT), Paragraph('', styleT), Paragraph('', styleT), Paragraph('', styleT) ], ] cols_width = [ 20 * mm, 50 * mm, 70 * mm, 25 * mm, ] tbl = Table(opinion, colWidths=cols_width) tbl.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 0.75, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) objs.append(Spacer(1, 5 * mm)) objs.append(tbl) else: table_value_result = table_part_result(table_value, width_max_table=180) if table_value_result: objs.append(table_value_result) objs.append(Spacer(1, 5 * mm)) if not doc_get_material: doc_get_material = dir.doc.get_fio() objs.append( Paragraph( f'19. Фамилия, инициалы врача: {doc_get_material} {space_symbol * 5} подпись _________', style)) objs.append( Paragraph(f'20. Дата направления: {strdate(dir.data_sozdaniya)}', style)) gistology_frame = Frame(0 * mm, 0 * mm, 210 * mm, 297 * mm, leftPadding=15 * mm, bottomPadding=16 * mm, rightPadding=7 * mm, topPadding=10 * mm, showBoundary=1) gistology_inframe = KeepInFrame(210 * mm, 297 * mm, objs, hAlign='LEFT', vAlign='TOP', fakeWidth=False) gistology_frame.addFromList([gistology_inframe], c)
def add_description(self, description, industries_type, file_path): base = path.basename(file_path) filename, file_extension = path.splitext(base) pdf_path = path.abspath(path.join(__file__, '../..')) + '/files/pdf/' millis = int(round(time.time())) water_pdf_name = 'watermark' + str(millis) + '.pdf' signature_pdf_name = 'signature' + str(millis) + '.pdf' output_pdf_name = 'Email:' + filename + str(millis) + '_signed.pdf' # create canvas for content c = canvas.Canvas(pdf_path + '/' + water_pdf_name, pagesize=GOV_LEGAL, bottomup=0) c_width, c_height = GOV_LEGAL # add background icolor = self._icolor(industries_type) c.drawImage(self.app.config['FILE_FOLDER'] + "/bg_{}.png".format(icolor), 0, 0, width=c_width, height=c_height, mask='auto', anchor='nw') # move the origin up and to the left c.translate(inch, inch) # change color if icolor == 3: c.setFillColorRGB(0, 0, 0) else: c.setFillColorRGB(255, 255, 255) # add handshake title c.setFont("Helvetica", 23) c.drawString(-10, 0.5 * inch, 'The Handshake') # define a large font stylesheet = getSampleStyleSheet() style = stylesheet['Normal'] style.fontName = 'Courier-Bold' style.fontSize = 34 style.leading = style.fontSize * 1.2 if icolor == 3: style.textColor = colors.black else: style.textColor = colors.white p = Paragraph(description, style) f = KeepInFrame(c_width + 20 - 2 * inch, c_height, [p], vAlign='TOP') width, height = f.wrapOn(c, c_width + 40 - 2 * inch, c_height) f.drawOn(c, -10, -height - 20 + (2.8 * inch)) c.showPage() c.save() # Get the watermark file you just created watermark = PdfFileReader(open(pdf_path + "/" + water_pdf_name, "rb")) signature = None # create signature page if any if len(description) > 160: c_signature = canvas.Canvas(pdf_path + '/' + signature_pdf_name, pagesize=GOV_LEGAL, bottomup=0) # add background c_signature.drawImage(self.app.config['FILE_FOLDER'] + "/bg_{}.png".format(icolor), 0, 0, width=c_width, height=c_height, mask='auto', anchor='nw') c_signature.showPage() c_signature.save() signature = PdfFileReader( open(pdf_path + "/" + signature_pdf_name, "rb")) # Get our files ready output_file = PdfFileWriter() watermark_page = watermark.getPage(0) output_file.addPage(watermark_page) if signature is not None: output_file.addPage(signature.getPage(0)) # finally, write "output" to document-output.pdf with open(pdf_path + output_pdf_name, "wb") as outputStream: output_file.write(outputStream) outputStream.close() return pdf_path + output_pdf_name
def print_test_pdf(): f = cat(os.path.dirname(__file__), 'test.pdf') cv = canvas.Canvas(f) def line(l, cv): cv.line(*tuple([l[0]*mm, (A4_h - l[1])*mm, l[2]*mm, (A4_h - l[3])*mm])) def text(s, cv, size=9, font='wtm', centered=False): cv.setFont(font, size) f = cv.drawCentredString if centered else cv.drawString f(*(s[0]*mm, (A4_h - s[1])*mm, unicode(s[2]))) def rect(s, cv, fill=0): cv.rect(s[0]*mm, (A4_h - s[1])*mm, 3*mm, 3*mm, fill=fill) def referral_form(cv): cv.setLineWidth(1*mm) cv.rect(8*mm, 12*mm, 192*mm, 265*mm) cv.setLineWidth(0.1*mm) lines = [ (8, 20, 200, 20), (8, 285, 200, 285), (8, 20, 8, 285), (200, 20, 200, 285), (14, 20, 14, 285), (20, 20, 20, 285), (8, 192, 200, 192), (20, 29, 200, 29), (20, 38, 200, 38), (20, 47, 200, 47), (14, 56, 200, 56), (63, 20, 63, 56), (110, 20, 110, 56), (155, 20, 155, 38), (14, 135, 200, 135), (14, 154, 200, 154), (14, 173, 200, 173), (14, 214, 200, 214), (14, 267, 200, 267), (63, 135, 63, 154), (69, 135, 69, 154), (155, 135, 155, 154), (161, 135, 161, 154), (110, 135, 110, 192), (116, 135, 116, 192), (63, 267, 63, 285), (69, 267, 69, 285), (110, 267, 110, 285), (116, 267, 116, 285), (155, 267, 155, 285), (161, 267, 161, 285), ] for s in lines: line(s, cv) s = [ (9, 25, u'轉'), (9, 80, u'出'), (9, 135, u'院'), (9, 190, u'所'), (9, 197, u'轉'), (9, 226, u'入'), (9, 255, u'院'), (9, 283, u'所'), (15, 25, u'被'), (15, 29, u'保'), (15, 33, u'險'), (15, 37, u'人'), (15, 41, u'基'), (15, 45, u'本'), (15, 49, u'資'), (15, 53, u'料'), (15, 60, u'病'), (15, 84, u'歷'), (15, 108, u'摘'), (15, 133, u'要'), (15, 140, u'診'), (15, 144, u'治'), (15, 148, u'醫'), (15, 152, u'師'), (64, 140, u'醫'), (64, 144, u'師'), (64, 148, u'簽'), (64, 152, u'章'), (111, 140, u'轉'), (111, 144, u'診'), (111, 148, u'目'), (111, 152, u'的'), (156, 140, u'聯'), (156, 144, u'絡'), (156, 148, u'方'), (156, 152, u'式'), (15, 159, u'轉'), (15, 163, u'診'), (15, 167, u'院'), (15, 171, u'所'), (15, 178, u'轉'), (15, 182, u'診'), (15, 186, u'日'), (15, 190, u'期'), (15, 197, u'處'), (15, 202, u'理'), (15, 207, u'情'), (15, 212, u'形'), (15, 219, u'治'), (15, 234, u'療'), (15, 249, u'摘'), (15, 265, u'要'), (15, 271, u'診'), (15, 275, u'治'), (15, 279, u'醫'), (15, 283, u'師'), (64, 271, u'科'), (64, 283, u'別'), (111, 159, u'地'), (111, 163, u'址'), (111, 167, u'電'), (111, 171, u'話'), (111, 178, u'開'), (111, 182, u'單'), (111, 186, u'日'), (111, 190, u'期'), (111, 271, u'醫'), (111, 275, u'師'), (111, 279, u'簽'), (111, 283, u'章'), (156, 271, u'回'), (156, 275, u'覆'), (156, 279, u'日'), (156, 283, u'期'), (202, 24, u'第'), (202, 28, u'一'), (202, 32, u'聯'), (202, 36, u':'), (202, 40, u'轉'), (202, 44, u'入'), (202, 48, u'院'), (202, 52, u'所'), (202, 56, u'留'), (202, 60, u'存'), (202, 64, u'。'), (202, 72, u'第'), (202, 76, u'二'), (202, 80, u'聯'), (202, 84, u':'), (202, 88, u'轉'), (202, 92, u'入'), (202, 96, u'院'), (202, 100, u'所'), (202, 104, u'回'), (202, 108, u'覆'), (202, 112, u'轉'), (202, 116, u'出'), (202, 120, u'院'), (202, 124, u'所'), (202, 128, u'。'), (202, 136, u'第'), (202, 140, u'三'), (202, 144, u'聯'), (202, 148, u':'), (202, 152, u'轉'), (202, 156, u'出'), (202, 160, u'院'), (202, 164, u'所'), (202, 168, u'留'), (202, 172, u'存'), (202, 176, u'。'), ] for ss in s: text(ss, cv, size=12) s = [ (10, 289, u'本轉診單限使用一次'), (21, 25.5, u'姓'), (58, 25.5, u'名'), (65, 25.5, u'性'), (104, 25.5, u'別'), (112, 25.5, u'出'), (125, 25.5, u'生'), (137, 25.5, u'日'), (150, 25.5, u'期'), (157, 25.5, u'身'), (170, 25.5, u'份'), (182, 25.5, u'證'), (195, 25.5, u'號'), (21, 43.5, u'聯'), (40, 43.5, u'絡'), (58, 43.5, u'人'), (65, 43.5, u'聯'), (78, 43.5, u'絡'), (91, 43.5, u'電'), (104, 43.5, u'話'), (112, 43.5, u'聯'), (140, 43.5, u'絡'), (167, 43.5, u'地'), (195, 43.5, u'址'), (25, 197, u'已予急診處置,並轉診至'), (25, 202, u'已安排本院'), (25, 207, u'已予適當處置並轉回原院所。建議事項如下:'), ] for ss in s: text(ss, cv, size=12) rect((21, 197), cv) rect((21, 202), cv) rect((21, 207), cv) text((105, 10, u'全民健康保險轉診單'), cv, size=20, centered=True) text((105, 18, u'轉診至'), cv, size=18, centered=True) typ = (u'急診治療', u'門診治療', u'住院治療', u'進一步檢查', u'轉出至適當院所繼續追蹤', u'其他') def referral(cv): s = [ (21, 34.5, u'魏筱筠'), # 姓名 (65, 34.5, u'女'), # 性別 (112, 34.5, '101-06-20'), # 出生日期 (157, 34.5, 'R220154944'), # 身份證號 (21, 52.5, u'魏媽媽'), # 聯絡人 (65, 52.5, '0920100200'), # 聯絡電話 (112, 52.5, u'台南市新營區民權路 30-1 號'), # 聯絡住址 (21, 142, u'魏筱筠'), # 診治醫師 (21, 150, u'婦產科'), # 診治醫師(科別) #(21, 104, '105-05-14'), # 聯絡方式 #(21, 104, '105-05-14'), # 轉診院所 #(21, 104, '105-05-14'), # 地址電話 #(21, 104, '105-05-20'), # 轉診日期 #(118, 104, '105-05-15'), # 開單日期 ] for ss in s: text(ss, cv, size=12, font='msjh') text((43, 18, u'惠生婦產科診所'), cv, size=18) text((8, 18, u'3521011033'), cv, size=16, font='msjh') referral_form(cv) referral(cv) style_sheet = getSampleStyleSheet() style = style_sheet['Normal'] style.fontName = 'msjh' style.fontSize = 12 style.leading = 14 frame1 = Frame(19*mm, 191*mm, 182*mm, 51*mm, showBoundary=0) s1 = u'''為提倡有科學根基的服務精神,中央氣象局依照職掌業務的範疇舉辦「天地人學思論壇」,邀請國內外具有國際聲望與影響力的學者分享其學術及人生的寶貴經驗,期能達到「天地人」和「學思論」分別呈現氣象局職掌業務與活動內容,藉由聆聽、討論、學習過程,擴大思考層面,深化科學涵養。活動相關訊息請參閱海報,竭誠歡迎大家報名參加。另「104年天地人學思論壇」產出的「氣象老先覺」專題電子版連結網址請「點此進入」,歡迎大家上網點閱,謝謝。為提倡有科學根基的服務精神,中央氣象局依照職掌業務的範疇舉辦「天地人學思論壇」,邀請國內外具有國際聲望與影響力的學者分享其學術及人生的寶貴經驗,期能達到「天地人」和「學思論」分別呈現氣象局職掌業務與活動內容,藉由聆聽、討論、學習過程,擴大思考層面,深化科學涵養。活動相關訊息請參閱海報,竭誠歡迎大家報名參加。另「104年天地人學思論壇」產出的「氣象老先覺」專題電子版連結網址請「點此進入」,歡迎大家上網點閱,謝謝。''' soap1 = [Paragraph(s1, style)] soap_in_frame1 = KeepInFrame(182*mm, 51*mm, soap1) frame1.addFromList([soap_in_frame1,], cv) # 轉診目的 frame2 = Frame(116*mm, 143*mm, 41*mm, 16*mm, showBoundary=0) s2 = typ[2] soap2 = [Paragraph(s2, style)] soap_in_frame2 = KeepInFrame(41*mm, 16*mm, soap2) frame2.addFromList([soap_in_frame2,], cv) cv.save()
def build_doc(self, fhandle): def text(s): return escape(s).replace("\n", "<br/>") doc = BaseDocTemplate(fhandle, pagesize=self.pagesize) frames = [ Frame( 15 * mm, 15 * mm, 100 * mm, 120 * mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='normal', ), Frame(125 * mm, 25 * mm, 70 * mm, 110 * mm, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='normal'), ] doc.addPageTemplates([ PageTemplate(id='AllPages', frames=frames, pagesize=self.pagesize, onPage=self._draw_qr) ]) meta = [] if self.obj.job_location: meta.append('Location: {}'.format(self.obj.job_location)) if self.obj.job_remote: meta.append('Remote') if self.obj.job_salary_range: meta.append('Salary: {}'.format(self.obj.job_salary_range)) meta = ' · '.join(meta) company_story = [] if self.obj.logo: im = Image(os.path.join(settings.MEDIA_ROOT, self.obj.logo.name), height=30 * mm, width=70 * mm, kind='proportional') company_story.append(im) company_story.append(Spacer(1 * mm, 3 * mm)) company_story.append( Paragraph(text(self.obj.company_name), style=self.stylesheet['Heading1']), ) company_story.append( Paragraph(text(self.obj.company_description), style=self.stylesheet['Normal']), ) if self.obj.company_contact: company_story.append(Spacer(1 * mm, 3 * mm)) company_story.append( Paragraph('Contact', style=self.stylesheet['Heading1']), ) company_story.append( Paragraph(text(self.obj.company_contact), style=self.stylesheet['Normal']), ) doc.build([ KeepInFrame( 110 * mm, 120 * mm, [ Paragraph(text(self.obj.job_title), style=self.stylesheet['Heading1']), Spacer(1 * mm, 2 * mm), Paragraph(text(meta), style=self.stylesheet['Meta']), Spacer(1 * mm, 2 * mm), Paragraph(text(self.obj.job_description), style=self.stylesheet['Normal']) ], mode='truncate'), FrameBreak(), KeepInFrame(70 * mm, 110 * mm, company_story, mode='truncate') ])
def render_statement(data, paragraphss, quarterly, fileName): doc = SimpleDocTemplate(fileName, pagesize=A4, rightMargin=72, leftMargin=56, topMargin=5, bottomMargin=18) Story = [] logo = "logos/toplogo.png" logo2 = "logos/bottomlogo.png" im = Image(logo, 8 * inch, 3 * inch) im2 = Image(logo2, 7 * inch, 1 * inch) t_keep = KeepInFrame(0, 0, Story, mode='shrink', hAlign='CENTER', vAlign='MIDDLE') lista = [data.columns[:, ].values.astype(str).tolist() ] + data.values.tolist() t1 = None if not quarterly: t1 = Table(lista, 4 * [1.5 * inch, 1.5 * inch, 2 * inch, 1.5 * inch], (len(lista)) * [0.3 * inch], hAlign='CENTER') else: t1 = Table(lista, 2 * [3.2 * inch, 3.2 * inch], (len(lista)) * [0.3 * inch], hAlign='CENTER') # t1.setStyle(TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'), # ('TEXTCOLOR', (1, 1), (-2, -2), colors.red), # ('VALIGN', (0, 0), (0, -1), 'TOP'), # ('TEXTCOLOR', (0, 0), (0, -1), colors.blue), # ('ALIGN', (0, -1), (-1, -1), 'CENTER'), # ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'), # ('TEXTCOLOR', (0, -1), (-1, -1), colors.green), # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # ('BOX', (0, 0), (-1, -1), 0.25, colors.black), # ])) t1.setStyle( TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('TEXTCOLOR', (0, -1), (-1, -1), colors.green), ('FONTNAME', (0, -1), (-1, -1), 'Courier-Bold')])) data_len = len(lista) for each in range(data_len): if each % 2 == 0: bg_color = colors.whitesmoke else: bg_color = colors.lightgrey t1.setStyle( TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) if each == data_len: t1.setStyle( TableStyle([('FONTNAME', (0, each), (0, each), 'Courier-Bold') ])) t1.setStyle( TableStyle([('BACKGROUND', (0, each), (0, each), colors.green) ])) Story.append(im) style = ParagraphStyle( name='Normal', fontSize=12, borderPadding=1, padding=1, alignment=TA_LEFT, leading=24, leftMargin=10, ) for x, y in paragraphss.items(): p = "" p += '<b>' + x + '</b>' + ":" + y p += "\n" Story.append(Paragraph(p, style=style)) Story.append(t1) Story.append(Spacer(1, 12)) Story.append(im2) Story.append(t_keep) doc.build(Story)
def first_pages(canvas, document): canvas.saveState() if closed_bl_result.get('is_closed', None): canvas.setFont('PTAstraSerifBold', 12) canvas.drawString(7 * mm, 290 * mm, 'ЛН') # Переведен transfers_text = [Paragraph('{}'.format(transfers), styleJustified)] transfers_frame = Frame(27 * mm, 206 * mm, 175 * mm, 7 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) transfers_inframe = KeepInFrame( 175 * mm, 12 * mm, transfers_text, hAlign='LEFT', vAlign='TOP', ) transfers_frame.addFromList([transfers_inframe], canvas) # Побочное действие лекарств(непереносимость) координаты medicament_text = [ Paragraph( '{}'.format(primary_reception_data['medicament_allergy']), styleJustified) ] medicament_frame = Frame(27 * mm, 171 * mm, 175 * mm, 9 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) medicament_inframe = KeepInFrame( 175 * mm, 12 * mm, medicament_text, hAlign='LEFT', vAlign='TOP', ) medicament_frame.addFromList([medicament_inframe], canvas) # ФИО fio_text = [ Paragraph( "<font size=11.7 fontname ='PTAstraSerifBold'> {}</font> ". format(patient_data['fio']), style) ] fio_frame = Frame(77 * mm, 159 * mm, 125 * mm, 8 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) fio_inframe = KeepInFrame( 175 * mm, 12 * mm, fio_text, hAlign='LEFT', vAlign='TOP', ) fio_frame.addFromList([fio_inframe], canvas) # Постоянное место жительства live_text = [Paragraph('{}, {}'.format(p_address, p_phone), style)] live_frame = Frame(88 * mm, 144 * mm, 115 * mm, 9 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) live_inframe = KeepInFrame( 175 * mm, 12 * mm, live_text, hAlign='LEFT', vAlign='TOP', ) live_frame.addFromList([live_inframe], canvas) # Место работы work_text = [Paragraph('{}'.format(p_work), style)] work_frame = Frame(108 * mm, 138.5 * mm, 95 * mm, 5 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) work_inframe = KeepInFrame( 175 * mm, 12 * mm, work_text, hAlign='LEFT', vAlign='TOP', ) work_frame.addFromList([work_inframe], canvas) # Кем направлен больной who_directed_text = [ Paragraph('{}'.format(primary_reception_data['who_directed']), style) ] who_directed_frame = Frame(77 * mm, 129.5 * mm, 126 * mm, 7 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) who_directed_inframe = KeepInFrame( 175 * mm, 12 * mm, who_directed_text, hAlign='LEFT', vAlign='TOP', ) who_directed_frame.addFromList([who_directed_inframe], canvas) # Диагноз направившего учреждения координаты diagnos_directed_text = [ Paragraph( '{}'.format(primary_reception_data['diagnos_who_directed']), styleJustified) ] diagnos_directed_frame = Frame(27 * mm, 98 * mm, 175 * mm, 9 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) diagnos_directed_inframe = KeepInFrame( 175 * mm, 10 * mm, diagnos_directed_text, hAlign='LEFT', vAlign='TOP', ) diagnos_directed_frame.addFromList([diagnos_directed_inframe], canvas) # Диагноз при поступлении координаты diagnos_entered_text = [ Paragraph('{}'.format(primary_reception_data['diagnos_entered']), styleJustified) ] diagnos_entered_frame = Frame(27 * mm, 83 * mm, 175 * mm, 10 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) diagnos_entered_inframe = KeepInFrame( 175 * mm, 10 * mm, diagnos_entered_text, hAlign='LEFT', vAlign='TOP', ) diagnos_entered_frame.addFromList([diagnos_entered_inframe], canvas) # клинический диагноз координаты diagnos_text = [ Paragraph('{}'.format(clinical_diagnos), styleJustified) ] diagnos_frame = Frame(27 * mm, 22 * mm, 175 * mm, 55 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) diagnos_inframe = KeepInFrame(175 * mm, 55 * mm, diagnos_text) diagnos_frame.addFromList([diagnos_inframe], canvas) # представитель пациента p_agent = None agent_status = '' agent = '' if ind_card.who_is_agent: p_agent = getattr(ind_card, ind_card.who_is_agent) agent_status = ind_card.get_who_is_agent_display() if p_agent: agent_data = p_agent.get_data_individual() agent_fio = agent_data['fio'] agent_phone = ','.join(agent_data['phone']) agent = f"{agent_status}: {agent_fio}, тел.:{agent_phone}" agent_text = [Paragraph('<u>{}</u>'.format(agent), styleRight)] agent_frame = Frame(27 * mm, 5 * mm, 175 * mm, 7 * mm, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='diagnos_frame', showBoundary=0) agent_inframe = KeepInFrame(175 * mm, 10 * mm, agent_text) agent_frame.addFromList([agent_inframe], canvas) canvas.restoreState()
def save_pdf(data): packet = BytesIO() can = canvas.Canvas(packet, pagesize=(595, 842)) can.translate(0, 842) can.drawString(246, -245, data['company_name']) can.drawString(246, -288, data['biz_sector']) can.drawString(246, -327, data['contact1']) can.drawString(246, -371, data['contact_designation']) can.drawString(59, -480, data['phone']) can.drawString(59, -535, data['NOE']) can.drawString(59, -432, data['biz_years']) #can.drawString(334, -430, data['doi']) can.drawString(334, -484, data['annual_revenue']) styles = getSampleStyleSheet() biz_improve = [Paragraph(data['biz_improve'], styles['Normal'])] biz_improve_inframe = KeepInFrame(215, 70, biz_improve) biz_improve_frame = Frame(320, -655, 215, 70) biz_improve_frame.addFromList([biz_improve_inframe], can) address = [Paragraph(data['company_address'], styles['Normal'])] address_inframe = KeepInFrame(215, 70, address) address_frame = Frame(51, -655, 215, 70) address_frame.addFromList([address_inframe], can) can.setFont("Helvetica-Bold", 25) can.setFillColor("blue") can.drawString(171, -750, data['score']) img_byte = BytesIO() photo = data['photo'] photo.seek(0) img_byte.write(photo.read()) img = Image.open(img_byte) img = resizeimage.resize_contain(img, [172, 182]) img = img.convert('RGB') thumb_io = BytesIO() img.save(thumb_io, "JPEG") img = ImageReader(thumb_io) can.drawImage(img, 51, -389) can.save() # move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader( open( os.path.join(settings.BASE_DIR, 'registrations', 'circuit_registration_form.pdf'), "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page2 = new_pdf.getPage(0) page.mergePage(page2) output.addPage(page) packet2 = BytesIO() packet2.seek(0) output.write(packet2) return packet2
def build_document(filename, images, name, drag): """ Takes a filename, a list of four PIL Image objects, a name and a value of drag and generates a PDF document. """ page = canvas.Canvas( filename, pagesize=(432, 288), ) rl_images = [convert_to_reportlab(image) for image in images] styles = get_styles() scw_bg.drawOn(page, 0, 0) img_width = 136.417 img_height = 102.313 x = [12, 151, 12, 151] y = [178.5, 178.5, 60, 60] for args in zip(rl_images, x, y): page.drawImage(*args, width=img_width, height=img_height) scw_logo.drawOn(page, 290, 107) erdf_logo.drawOn(page, 290, 7.184) name = KeepInFrame(275, 41.3, [Paragraph(name, styles["Normal"])], mode='shrink') name.wrapOn(page, 275, 46) name.drawOn(page, 20, 9) drag_caption = KeepInFrame(127.559, 20.272, [Paragraph("Drag", styles["Heading2"])], mode='shrink') drag_caption.wrapOn(page, 127.559, 20.272) drag_caption.drawOn(page, 289, 256.5) drag_figure = KeepInFrame( 127.559, 50.551, [Paragraph("{drag:.1f}".format(drag=drag), styles["Heading2"])], mode='shrink') drag_figure.wrapOn(page, 127.559, 50.551) drag_figure.drawOn(page, 289, 210) page.showPage() page.save() print("pdf file saved to {filename}".format(filename=filename))
def __init__(self, content=[], maxWidth=0, maxHeight=0, zoom=1, **kwargs): if content and not hasattr(content, '__iter__'): raise ValueError('content expected to be a list of flowables') self.zoom = zoom KeepInFrame.__init__(self, maxWidth, maxHeight, content=content, **kwargs)