def create_first_page(): TOP = (29.7 - 5) * cm LEFT = 4 * cm RIGHT = (21 - 4) * cm FONT_SIZE = 10 FONT = "Plex" text = "PyJournal year 2020" image_path = "logo.png" # text right font = FONT font_size = FONT_SIZE canvas = Canvas("first_page.pdf", pagesize=A4) canvas.setFont(font, font_size) canvas.setFillColor(black) text_width = pdfmetrics.stringWidth(text, font, font_size) text_height = int(FONT_SIZE * 1.2) # TODO not correct canvas.drawString(RIGHT - text_width, TOP - text_height, text) # logo img = utils.ImageReader(image_path) img_width, img_height = img.getSize() aspect = img_height / float(img_width) display_width = 100 display_height = (display_width * aspect) canvas.drawImage(image_path, LEFT, TOP - display_height, width=display_width, height=display_height, mask="auto") canvas.save()
def ccPDFmake(frontFile, backFile, saveFile, text): canvas = Canvas(saveFile) front = utils.ImageReader(frontFile) back = utils.ImageReader(backFile) canvas.drawImage(front, FRONT_X, FRONT_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') canvas.drawImage(back, BACK_X, BACK_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') if text != "": canvas.saveState() canvas.rotate(55) canvas.setFillColorRGB(.6, .6, .6) canvas.setFont("Times-Roman", 30) canvas.drawString(10 * CM, 0.2 * CM, text) canvas.restoreState() canvas.save() return True
def draw_address(self, loader, font, font_size): name = loader.get_name() if loader.has_logo(): print("has_logo") path = "database/logos/" + name + ".png" img = utils.ImageReader(path) img_width, img_height = img.getSize() self.y_cursor -= img_height / mm self.c.drawImage("database/logos/" + name + ".png", (self.page_width - img_width / mm) / 2.0, self.y_cursor, width=img_width / mm, height=img_height / mm, preserveAspectRatio=True, anchor='c') self.y_cursor -= 10 self.draw_object(name, font, font_size) address = loader.get_address()[0] self.draw_object(address, font, font_size) phone = loader.get_phone() self.draw_object(phone, font, font_size) self.y_cursor -= 10
def resize_image(image_file): """ Get the image ready. Change the dimensions if needed to fit on the page :param image_file: :return: """ if os.path.isfile(image_file): try: img = utils.ImageReader(image_file) xsize, ysize = img.getSize() width, height = A4 width = width - (MARGIN_SIZE * 2) height = height - (BOTTOM_MARGIN + TOP_MARGIN) if xsize > ysize: # deal with cases were xsize is bigger than ysize if xsize > width: xsize_corrected = width ysize_corrected = int(ysize * (xsize_corrected / xsize)) return Image(image_file, width=xsize_corrected, height=ysize_corrected) else: # deal with cases where ysize is bigger than xsize if ysize > height: ysize_corrected = height a = ysize_corrected / ysize xsize_corrected = xsize * a return Image(image_file, width=xsize_corrected, height=ysize_corrected) return Image(image_file) except OSError: return None return None
def addHbcHeader(self): c = self.c top = self.top S = ParagraphStyle('dflt-right') S.alignment = 2 img = utils.ImageReader('logoHD.png') iw, ih = img.getSize() aspect = ih / float(iw) width = 200 I = Image('logoHD.png', width=width, height=(width * aspect)) w, h = I.wrap(200, 50) I.drawOn(self.c, 14 * cm, top - h - 1 * cm) P = Paragraph( "<strong>HEADBANG CLUB</strong><br/>" + "15 RUE FERDINAND BUISSON<br/>" + "16160 GOND-PONTOURE<br/>CHARENTE - FRANCE<br/>" + "VAT - FR63824464127<br/>" + "TEL - +33 (0)6 63 92 55 96<br/>" + "[email protected] / [email protected]", S) w, h = P.wrap(300, 50) P.drawOn(self.c, 21 * cm - w - 0.5 * cm, self.top - h - 4 * cm) pass
def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) preserveAspectRatio = args.pop('preserveAspectRatio', False) if preserveAspectRatio: img = utils.ImageReader(args['filename']) args['filename'].seek(0) iw, ih = img.getSize() if 'width' in args and 'height' not in args: args['height'] = args['width'] * ih / iw elif 'width' not in args and 'height' in args: args['width'] = args['height'] * iw / ih elif 'width' in args and 'height' in args: # In this case, the width and height specify a bounding box # and the size of the image within that box is maximized. if args['width'] * ih / iw <= args['height']: args['height'] = args['width'] * ih / iw elif args['height'] * iw / ih < args['width']: args['width'] = args['height'] * iw / ih else: # This should not happen. raise ValueError('Cannot keep image in bounding box.') else: # No size was specified, so do nothing. pass vAlign = args.pop('vAlign', None) hAlign = args.pop('hAlign', None) img = self.klass(**args) if hAlign: img.hAlign = hAlign if vAlign: img.vAlign = vAlign self.parent.flow.append(img)
def draw_logo(self, canvas): """ Draw the logo on pdf according to following settings: logo_path: absolute path to image wanted_height: wanted height in mm (optional, default 20 mm) logo_x: x coordinate in mm (optional, default 13 mm) logo_y: y coordinate in mm (optional, default 55 mm) """ if not self.company_logo_settings: return # Get logo settings logo_path = self.company_logo_settings.get('path', None) wanted_height = self.company_logo_settings.get('wanted_height', 20) logo_x = self.company_logo_settings.get('x', 13) logo_y = self.company_logo_settings.get('y', 55) # Sanity check if not os.access(logo_path, os.R_OK): return # get original lgo dimensions to compute ratio logo = utils.ImageReader(logo_path) width, height = logo.getSize() ratio = float(width) / height # Compute width according to wanted height computed_width = int(wanted_height * ratio) # Draw logo im = Image(logo_path, computed_width * mm, wanted_height * mm) im.drawOn(canvas, *self.coord(logo_x, logo_y))
def getImage(filename, width, dummy=False): filename = os.path.normpath(filename) # The module only uses the file extension, it would be better to use python-magic but # this requires to install yet another module with pip. So this is sufficient for now. imageType = mime.guess_type(filename)[0] if imageType in allowedImages: orig = utils.ImageReader(filename) iw, ih = orig.getSize() aspect = ih / float(iw) height = width * aspect img = Image(filename, width=width, height=height) # Allow to insert a PDF page as an image, just like LaTeX does, this allows to insert # vector graphics. elif imageType == "application/pdf": pages = PDFSinglePage(filename, width=width, index=0) height = img.height else: print("Unsupported image type " + imageType + " for " + filename) img = Spacer(width, width / 2) height = img.width / 2 return DummyFlowable(Spacer(width, height), img, dummy)
def template_inv(c): c.translate(cm,cm) x = 0*cm y = 2.5*cm # LOGO img = "files/CBM_E_TrakindoLogo.png" img_read = utils.ImageReader(img) img_width, img_height = img_read.getSize() c.drawImage(img, x, y+24*cm, img_width / 16, img_height / 16, mask='auto') # 1 c.setFont('Univers_67_Condensed_Bold', 9) c.drawString(x+3.2*cm, y+23.7*cm, 'PTTrakindo Utama') # 2 c.setFont('Univers_67_Condensed_Bold', 11) c.drawString(x+3.2*cm, y+21.8*cm, 'FAKTUR PENJUALAN') c.setFont('Univers_57_Condensed', 11) c.drawString(x+6.6*cm, y+21.8*cm, ' / INVOICE') # 3 c.setFont('Univers_57_Condensed', 11) c.drawString(x+3.2*cm, y+21*cm, 'SOLD TO') c.drawString(x+12.4*cm, y+21*cm, 'CONSIGNED TO') # 4 strFooter1 = 'Barang-barang tidak boleh dikembalikan. Keberatan/pengaduan tidak dilayani jika barang telah keluar dari gudang kami' strFooter2 = 'Goods are not returnable. Claims will not be accepted once goods have left our ware house' c.setFont('Univers_57_Condensed', 8) c.drawCentredString(9.5*cm, -0.2*cm, strFooter1) c.setFont('Univers_LT_67_Condensed_Bold_Oblique', 8) c.drawCentredString(9.5*cm, -0.5*cm, strFooter2)
def _header_footer(canvas, doc): # Save the state of our canvas so we can draw on it canvas.saveState() styles = getSampleStyleSheet() # Header img = utils.ImageReader('https://www.martinhelder.pt/img/logotipo.png') img_w, img_h = img.getSize() header = Image('https://www.martinhelder.pt/img/logotipo.png', width=0.7 * img_w, height=0.7 * img_h) width, height = header.wrap(doc.width, doc.topMargin) header.drawOn(canvas, doc.leftMargin + 0 * width, doc.height + doc.topMargin - height + 35) # Footer right = ParagraphStyle('BodyText', alignment=TA_RIGHT, fontName='Vera') footer = Table([[ Paragraph(str(doc.page), styles['BodyText']), Paragraph( "Documento gerado a " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), right) ]], colWidths=(None, 0.8 * doc.width)) footer.wrap(doc.width, doc.topMargin) footer.drawOn(canvas, doc.leftMargin, 0.6 * doc.bottomMargin) # Release the canvas canvas.restoreState()
def alter_aspect(path, width) : im = utils.ImageReader(path) w, h = im.getSize() logging.info((w, h)) aspect = float(width / w) logging.info(aspect) return Image(path,width, h*aspect)
def reporte(request): response = HttpResponse(content_type="application/pdf") response['Content-Disposition'] = 'attachment; filename=codigoQR.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) c.setFont("Helvetica-Bold", 24) c.drawString(50, 750, "Ruc:") c.setFont("Helvetica", 24) c.drawString(110, 750, str(RUC)) c.setFont("Helvetica-Bold", 24) c.drawString(50, 700, "Nombre :") c.setFont("Helvetica", 24) c.drawString(160, 700, str(Nombre)) c.drawImage(utils.ImageReader(img._img), 50, 150, 500, 500, preserveAspectRatio=True) c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) os.remove(settings.MEDIA_ROOT + "/image/" + str(RUC) + ".png") return response
def get_image(self, path, width=None, height=None, max_width=0, max_height=0): """Retrieves the image via the link and gets the size from the image. The correct dimensions for image are calculated based on the desired with or height""" try: #Read image from link img = utils.ImageReader(path) except: return None #Get Size imgWidth, imgHeight = img.getSize() #Detect if there height or width provided if width and height == None: ratio = float(imgHeight) / float(imgWidth) new_height = ratio * width new_width = width elif height and width == None: ratio = float(imgWidth) / float(imgHeight) new_height = height new_width = ratio * height if max_width != 0 and new_width > max_width: new_width = max_width new_height = (float(imgHeight) / float(imgWidth)) * max_width return Image(path, width=new_width, height=new_height)
def __getImageAspectRatio(self, filename): # returns the aspect ratio for resizing images in a proportional manner # eg: newHeight = newWidth * getImageAspectRatio() from reportlab.lib import utils img = utils.ImageReader(filename) w, h = img.getSize() return (h / w)
def get_image(self, path, width=3*inch, alignement='LEFT'): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) final_im = Image(path, width=width, height=(width * aspect)) final_im.hAlign = alignement return final_im
def easy_draw(): dirw = '/home/youngn/zhoup/Data/web' fignames = ["%d.jpg" % num for num in range(1, 5)] figs = [op.join(dirw, figname) for figname in fignames] c = canvas.Canvas(op.join(dirw, 'ex2.pdf')) for i in range(0, 4): img = utils.ImageReader(figs[i]) iw, ih = img.getSize() aspect = ih / float(iw) wd = 10 ht = wd * aspect gap = 0.5 x = (wd + gap) * i * cm # c.drawImage(figs[i], x, wd*cm, width = wd*cm, height = wd*aspect*cm) if i == 0: c.drawImage(figs[i], gap * 2 * cm, (gap * 2 + wd) * cm, width=wd * cm, height=ht * cm) elif i == 1: c.drawImage(figs[i], (gap * 2 + wd) * cm, (gap * 2 + wd) * cm, width=wd * cm, height=ht * cm) elif i == 2: c.drawImage(figs[i], gap, gap, width=wd * cm, height=ht * cm) elif i == 3: c.drawImage(figs[i], (gap * 2 + wd) * cm, gap, width=wd * cm, height=ht * cm) else: print "error: %d figs" % len(figs) c.showPage() c.save()
def get_image(path, width=1*cm): """ Reshape an image with the good ratio """ img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect))
def draw(self): img = utils.ImageReader(self.image) iw, ih = img.getSize() aspect = ih / float(iw) width, self.height = PAGE_SIZE width -= 3.5*cm self.canv.drawImage(os.path.join(BASE_DIR , self.image) , -1 *MARGIN_SIZE + 1.5*cm , -1* self.height + 5*cm , width, aspect*width)
def get_image(image, width=1 * cm): img = utils.ImageReader(image) iw, ih = img.getSize() aspect = ih / float(iw) if isinstance(image, ImageFieldFile): image.seek(0) return Image(image, width=width, height=(width * aspect))
def get_image(path, width=1 * inch, height=1 * inch): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) if width * aspect > height: return Image(path, width=(height / aspect), height=height) else: return Image(path, width=width, height=(width * aspect))
def draw_image(self, path, x, y, width): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) self.m_canvas.drawImage(path, x, y, width=width, height=(width * aspect))
def get_image_size(path, available_width, available_height): img = utils.ImageReader(path) image_width, image_height = img.getSize() width_ratio = available_width / image_width height_ratio = available_height / image_height best_ratio = min(width_ratio, height_ratio) return (image_width * best_ratio, image_height * best_ratio)
def write(self): """Assembles the final PDF and writes to disk.""" pdf_writer = pyPdf.PdfFileWriter() if self.front_matter is not None: front_matter = pyPdf.PdfFileReader(file(self.front_matter, "rb")) for page in range(front_matter.getNumPages()): pdf_writer.addPage(front_matter.getPage(page)) working_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) doc = SimpleDocTemplate(working_file) doc.pagesize = portrait(letter) story = [] styles = getSampleStyleSheet() for section in self.sections: heading_text = section.heading story.append(Paragraph(heading_text, styles['Heading1'])) for content in section.contents: if 'figure' in content: figure = content['figure'] if os.path.exists(figure): im = utils.ImageReader(figure) img_width, img_height = im.getSize() aspect = img_height / float(img_width) story.append( Image(figure, width=img_width, height=(img_width * aspect))) if content.get('caption', None) is not None: caption_text = '<font size=10>{0}</font>'.format( content['caption'].strip()) story.append(Paragraph(caption_text, styles['Italic'])) story.append(Spacer(1, 10)) if 'table' in content: _t = self.build_table(content['table']) story.append(_t) if content.get('caption', None) is not None: caption_text = '<font size=10>{0}</font>'.format( content['caption'].strip()) story.append(Paragraph(caption_text, styles['Italic'])) story.append(Spacer(1, 10)) if 'text' in content: for para in content['text']: story.append(Paragraph(para, styles['Normal'])) story.append(Spacer(1, 12)) doc.build(story) body_matter = pyPdf.PdfFileReader(working_file) for page in range(body_matter.getNumPages()): pdf_writer.addPage(body_matter.getPage(page)) try: os.remove(working_file.name) except OSError: # Windows reports file in use, other OS errors, etc. pass if self.end_matter is not None: end_matter = pyPdf.PdfFileReader(file(self.end_matter, "rb")) for page in range(end_matter.getNumPages()): pdf_writer.addPage(end_matter.getPage(page)) output_stream = file(self.output_filename, "wb") pdf_writer.write(output_stream)
def _create_header(self, canvas, doc): #Draw the logo in the upper left if self.company.lower() == 'dellarobbia thailand': path = """https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/form_logo.jpg""" else: path = "https://s3-ap-southeast-1.amazonaws.com/media.dellarobbiathailand.com/logo/Alinea-Logo_Master.jpg" # Read image from link img = utils.ImageReader(path) # Get Size img_width, img_height = img.getSize() new_width = (img_width * logo_height) / img_height canvas.drawImage(path, 42, 760, height=logo_height, width=new_width) canvas.setFont('Helvetica', 8) canvas.setFillColorCMYK(0, 0, 0, 60) #Add Company Information in under the logo if dellarobbia if self.company.lower() == 'dellarobbia thailand': canvas.drawString(42, 760, "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka") canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150") canvas.drawString(42, 740, "+66 2 508 8681") else: canvas.drawString(42, 760, "78/448 Moo.6 Lam Lukka Rd. Bueng Kham Phroi, Lam Lukka") canvas.drawString(42, 750, "Pathum Thani, Thailand, 12150") canvas.drawString(42, 740, "+66 2 508 8681") #canvas.drawString(42, 730, "www.dellarobbiathailand.com") # Create The document type and document number canvas.setFont("Helvetica", 16) canvas.drawRightString(550, 800, 'Purchase Order') canvas.setFont("Helvetica", 12) canvas.drawRightString(550, 780, 'PO# : {0}'.format(self.id)) # Create a barcode from the id canvas.setFillColorCMYK(0, 0, 0, 1) code = 'PO-{0}'.format(self.id) barcode = code128.Code128(code, barHeight=20, barWidth=0.5 * mm) x_position = 570 - barcode.width # drawOn puts the barcode on the canvas at the specified coordinates barcode.drawOn(canvas, x_position, 750) # Create the revision if self.revision: if self.revision_date: msg = u"Revision: {0}, # {1}" revision_str = msg.format(self.revision_date.strftime('%B %d, %Y'), self.revision) else: msg = u'Revision: # {0}' revision_str = msg.format(self.revision) canvas.setFillColorCMYK(0, 0, 0, 1) canvas.setFont("Helvetica", 12) canvas.drawRightString(550, 730, revision_str)
def add_course_org_logo(self): if not self.organizations: return # Fetch the organization data organization = self.organizations[0] organization_name = organization.get('name') logo = organization.get('logo', None) if not logo.name: return x = self.left_panel_center y = 5.9 text = self._("Brought to you by") self.draw_bidi_center_text(text, x, y, 0.15, color='grey-light') # Underline the sentence text_width = stringWidth(text, self.font, self.font_size) length = text_width if self.is_english else -text_width xu = self.bidi_x_axis(x * inch, offset=length / 2.0) yu = (y - 0.1) * inch self.ctx.setStrokeColor(self.colors['grey-light']) self.ctx.setLineWidth(0.5) self.ctx.line(xu, yu, xu + length, yu) try: image = utils.ImageReader(self.path_builder(logo.url)) iw, ih = image.getSize() aspect = iw / float(ih) except (IOError, ValueError): image = None iw, aspect = 0, 0 height = inch width = height * aspect if aspect > 2: # in case the logo is too wide width = 2 * inch height = width / aspect x = self.bidi_x_axis(x * inch, offset=width / 2.0) y -= 1.3 self.ctx.drawImage(image, x, y * inch, width, height, mask='auto') x = self.left_panel_center y -= 0.15 self.draw_bidi_center_text(organization_name, x, y, 0.09, color='grey-light')
def get_image(path, width=1 * cm): """ Extract an image to a given size (specified by a given width) without altering width and height ratios """ img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect))
def get_image(x, y, path, width): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return pdf.drawImage(x=x, y=y, image=path, width=width, height=(width * aspect), mask='auto')
def InsertImage(path, c, width, cursor): # Adjust aspect ratio img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) img = Image(path, width=width, height=(width * aspect)) img.drawOn(c, 0, cursor) cursor -= img.imageHeight return cursor
def get_image(path, width=1 * cm): """ Get a thumbnail of the logo to display on the invoice page """ img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return AlignedImage(path, hAlign="CENTER", width=width, height=(width * aspect))
def get_image(path, width=1 * cm): """ Загружает изображение и пропорционально масштабирует высоту и ширину :param path: Путь к изображению :param width: Ширина для отображения :return: Ссылку на изображение """ img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect))