def _image(self, node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute("file"))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ("width", "height", "x", "y"): if node.hasAttribute(tag): args[tag] = utils.unit_get(node.getAttribute(tag)) if ("width" in args) and (not "height" in args): args["height"] = sy * args["width"] / sx elif ("height" in args) and (not "width" in args): args["width"] = sx * args["height"] / sy elif ("width" in args) and ("height" in args): if (float(args["width"]) / args["height"]) > (float(sx) > sy): args["width"] = sx * args["height"] / sy else: args["height"] = sy * args["width"] / sx self.canvas.drawImage(img, **args)
def render(self, canvas): if os.path.isfile(self.link): im = ImageReader(self.link) #pdb.set_trace() size = int(self.height / mm * 2.8) hh = size ww = int(im.getSize()[0] * hh / im.getSize()[1]) #im.thumbnail((size, size)) canvas.drawImage(im, self.position[0], self.position[1], ww, hh) else: print "File", self.link, "not found."
def render(self, canvas): if os.path.isfile(self.link): im = ImageReader(self.link) #pdb.set_trace() size = int(self.height/mm*2.8) hh = size ww = int(im.getSize()[0]*hh/im.getSize()[1]) #im.thumbnail((size, size)) canvas.drawImage(im, self.position[0], self.position[1], ww, hh) else: print "File", self.link, "not found."
class Image(SimpleChunk): """An image.""" def __init__(self, filename, zoom=100, raised_by=0): self.filename = filename self.zoom = zoom self.raised_by = raised_by self.image = ImageReader(filename) def size(self, canvas, w, h): myw, myh = self.image.getSize() myw = myw * self.zoom / 100 myh = myh * self.zoom / 100 return myw, myh def drawOn(self, canvas, x, y, w, h): myw, myh = self.size(canvas, w, h) raised_by = self.raised_by * myh / 100 try: canvas.drawImage(self.filename, x, y - myh + raised_by, myw, myh, mask='auto') except Exception: log.debug("Exception in canvas.drawImage:", exc_info=True) log.warning("Could not render image %s", self.filename) return x + myw, y def __str__(self): return '[%s]' % self.filename
def createImage(self, fn, aspect=None, width=None, height=None, indent=None, padding=10, shift=True, return_image=False): _, file_extension = os.path.splitext(fn) if file_extension.lower().strip() == '.pdf': logger.critical('Doesnt WORK ON PDFS yet') raise #Get image dimensions img = ImageReader(fn) iw, ih = img.getSize() #Set parameters if aspect is None: if width is None and height is None: width = iw height = ih elif height is None: aspect = float(ih) / float(iw) height = aspect * width elif width is None: aspect = float(iw) / float(ih) width = aspect * height else: width = iw * aspect height = ih * aspect if height > self.mheight: logger.warning('Image is taller than the entire page') if width + (indent or 0.0) > self.mwidth: logger.warning('Entering side margin...check') i = Image(fn, width=width, height=height) if return_image: return i #Shif down before adding to make room if shift: self.shiftPos(height + padding) #Indent if necessary if not indent is None: self.c.saveState() self.c.translate(indent, 0) #Draw the image i.drawOn(self.c, self.pos[0], self.pos[1]) #Restore if needed if not indent is None: self.c.restoreState() return width, height
def download_manka(dic, db): page = 0 match_obj = re.match(f'(.*)(\..*)', dic['img_url']) head = match_obj.group(1) tail = match_obj.group(2) c = None if dic['img_url'] != str.strip(dic['img_url']): print('NOT EQ') exit(0) c = Canvas(dic['name'] + '.pdf') try: while True: page += 1 print(f'Downloading Page{page}') image = ImageReader(f'{head}{page:d}{tail}') c.setPageSize(image.getSize()) c.drawImage(image, 0, 0, mask='auto') c.showPage() except OSError: if page == 1: return 0 pass page -= 1 if c: c.save() print('Done') return page
def process_text(node, new_node): if new_node.tag in ['story', 'tr', 'section']: new_node.attrib.clear() for child in utils._child_get(node, self): new_child = copy.deepcopy(child) new_node.append(new_child) if len(child): for n in new_child: new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail) new_child.remove(n) process_text(child, new_child) else: if new_child.tag == 'img' and new_child.get('name'): if _regex.findall(new_child.get('name')): src = utils._process_text(self, new_child.get('name')) if src: new_child.set('src', 'data:image/gif;base64,%s' % src) output = cStringIO.StringIO( base64.decodestring(src)) img = ImageReader(output) (width, height) = img.getSize() if not new_child.get('width'): new_child.set('width', str(width)) if not new_child.get('height'): new_child.set('height', str(height)) else: new_child.getparent().remove(new_child) new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail)
def __logo_line(self): canvas = self.canv current_y, current_x = self.current_y, self.current_x canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO_SM) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, HEADER_MARGIN, current_y - (dpaw_header_logo_size[1] / 1.8), height=dpaw_header_logo_size[1] / 1.8, mask='auto', width=dpaw_header_logo_size[0] / 1.8) current_y = -20 canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) canvas.drawRightString(current_x * 45, current_y, 'Remittance Advice') #current_y -= 20 #canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) #canvas.drawString(current_x * 27,current_y,'PLEASE DETACH AND RETURN WITH YOUR PAYMENT') current_y -= 50 canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) canvas.drawString(current_x, current_y, 'ABN: 38 052 249 024') self.current_y = current_y
def _image(self, node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute('file'))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx,sy) = img.getSize() args = {} for tag in ('width','height','x','y'): if node.hasAttribute(tag): args[tag] = utils.unit_get(node.getAttribute(tag)) if node.hasAttribute("preserveAspectRatio"): args["preserveAspectRatio"] = True if node.hasAttribute("mask"): args["mask"] = node.getAttribute("mask") if node.hasAttribute("anchor"): args["anchor"] = node.getAttribute("anchor") if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args) and (not args.get("preserveAspectRatio", False)): #if (float(args['width'])/args['height'])>(float(sx)>sy): # args['width'] = sx * args['height'] / sy #else: # args['height'] = sy * args['width'] / sx pass self.canvas.drawImage(img, **args)
def resolve_image(self, node): # Get filename from image node attribute file filename = str(node.getAttribute('file')) # Try resolving filename from image resource directories try: path = find_resource_abspath(filename, self.image_dirs) except ValueError: # On fail, return None return None, None # Open the file on the image reader fd = file(path, "r") img = ImageReader(fd) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): args[tag] = t2putils.as_pt(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width'])/args['height'])>(float(sx)>sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx return img, args
def process_text(node,new_node): if new_node.tag in ['story','tr','section']: new_node.attrib.clear() for child in utils._child_get(node, self): new_child = copy.deepcopy(child) new_node.append(new_child) if len(child): for n in new_child: new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail) new_child.remove(n) process_text(child, new_child) else: if new_child.tag=='img' and new_child.get('name'): if _regex.findall(new_child.get('name')) : src = utils._process_text(self, new_child.get('name')) if src : new_child.set('src','data:image/gif;base64,%s'%src) output = cStringIO.StringIO(base64.decodestring(src)) img = ImageReader(output) (width,height) = img.getSize() if not new_child.get('width'): new_child.set('width',str(width)) if not new_child.get('height') : new_child.set('height',str(height)) else : new_child.getparent().remove(new_child) new_child.text = utils._process_text(self, child.text) new_child.tail = utils._process_text(self, child.tail)
def makeRawImage(filename, IMG=None, detectJpeg=False): import zlib img = ImageReader(filename) if IMG is not None: IMG.append(img) if detectJpeg and img.jpeg_fh(): return None imgwidth, imgheight = img.getSize() raw = img.getRGBData() code = [] append = code.append # this describes what is in the image itself append('BI') append('/W %s /H %s /BPC 8 /CS /%s /F [/Fl]' % (imgwidth, imgheight, _mode2cs[img.mode])) append('ID') #use a flate filter assert len(raw) == imgwidth * imgheight * _mode2bpp[ img.mode], "Wrong amount of data for image" compressed = zlib.compress(raw) #this bit is very fast... #append in blocks of 60 characters _chunker(compressed, code) append('EI') return code
def resolve_image(self, node): # Get filename from image node attribute file filename = str(node.getAttribute('file')) # Try resolving filename from image resource directories try: path = find_resource_abspath(filename, self.image_dirs) except ValueError: # On fail, return None return None, None # Open the file on the image reader fd = file(path, "r") img = ImageReader(fd) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): args[tag] = t2putils.as_pt(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width']) / args['height']) > (float(sx) > sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx return img, args
def _image(self, node): #add attribute 'src' to tag 'image' by xiandong.xie s = StringIO.StringIO() if node.hasAttribute('src'): import base64 imgdata = base64.b64decode(node.getAttribute('src')) s.write(imgdata) else: import urllib u = urllib.urlopen(str(node.getAttribute('file'))) s.write(u.read()) from reportlab.lib.utils import ImageReader s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): args[tag] = utils.unit_get(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width']) / args['height']) > (float(sx) > sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def makeRawImage(filename,IMG=None,detectJpeg=False): import zlib img = ImageReader(filename) if IMG is not None: IMG.append(img) if detectJpeg and img.jpeg_fh(): return None imgwidth, imgheight = img.getSize() raw = img.getRGBData() code = [] append = code.append # this describes what is in the image itself append('BI') append('/W %s /H %s /BPC 8 /CS /%s /F [/Fl]' % (imgwidth, imgheight,_mode2cs[img.mode])) append('ID') #use a flate filter assert len(raw) == imgwidth * imgheight*_mode2bpp[img.mode], "Wrong amount of data for image" compressed = zlib.compress(raw) #this bit is very fast... #append in blocks of 60 characters _chunker(compressed,code) append('EI') return code
def makeA85Image(filename, IMG=None): import zlib img = ImageReader(filename) if IMG is not None: IMG.append(img) imgwidth, imgheight = img.getSize() raw = img.getRGBData() code = [] append = code.append # this describes what is in the image itself append('BI') append('/W %s /H %s /BPC 8 /CS /%s /F [/A85 /Fl]' % (imgwidth, imgheight, _mode2cs[img.mode])) append('ID') #use a flate filter and Ascii Base 85 assert len(raw) == imgwidth * imgheight * _mode2bpp[ img.mode], "Wrong amount of data for image" compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this may not be #append in blocks of 60 characters _chunker(encoded, code) append('EI') return code
def _image(self, node): from six.moves import urllib from reportlab.lib.utils import ImageReader u = urllib.request.urlopen("file:" + str(node.getAttribute('file'))) s = io.BytesIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): # if not utils.unit_get(node.getAttribute(tag)): # continue args[tag] = utils.unit_get(node.getAttribute(tag)) if node.hasAttribute("preserveAspectRatio"): args["preserveAspectRatio"] = True if node.hasAttribute('mask'): args['mask'] = node.getAttribute('mask') if ('width' in args) and ('height' not in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and ('width' not in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args) and (not args.get("preserveAspectRatio", False)): if (float(args['width']) / args['height']) > (float(sx) > sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def _image(self, node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute('file'))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx,sy) = img.getSize() args = {} for tag in ('width','height','x','y'): if node.hasAttribute(tag): if not utils.unit_get(node.getAttribute(tag)): continue args[tag] = utils.unit_get(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width'])/args['height'])>(float(sx)>sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def _image(self, node): from six.moves import urllib from reportlab.lib.utils import ImageReader u = urllib.request.urlopen("file:" + str(node.getAttribute('file'))) s = io.BytesIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): # if not utils.unit_get(node.getAttribute(tag)): # continue args[tag] = utils.unit_get(node.getAttribute(tag)) if node.hasAttribute("preserveAspectRatio"): args["preserveAspectRatio"] = True if node.hasAttribute('mask'): args['mask'] = node.getAttribute('mask') if ('width' in args) and ('height' not in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and ('width' not in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args) and (not args.get( "preserveAspectRatio", False)): if (float(args['width']) / args['height']) > (float(sx) > sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def main(): if len(sys.argv) < 2: print("Syntax: {0} <Image Directory> <Output File>".format(__file__)) return 1 image_dir = sys.argv[1] output_file = sys.argv[2] if not output_file.endswith(".pdf"): output_file += ".pdf" file_list = [] for filename in os.listdir(image_dir): if len(filename) >= 4 and filename[-4:] in ALLOWED_EXTENSIONS: file_list.append(os.path.join(image_dir, filename)) print("Make a PDF slide at {0} from images in the following order:".format(output_file)) pdf = canvas.Canvas(output_file, pageCompression=True) for i, filepath in enumerate(sorted(file_list)): print("[{2}/{1}] {0}".format(filepath, len(file_list), i+1)) image = ImageReader(filepath) pdf.setPageSize(image.getSize()) pdf.drawImage(image, 0, 0) pdf.showPage() pdf.save()
def create_image_pdf(images, args): c = canvas.Canvas(args.output) format = A4 if args.landscape: c.setPageSize(landscape(A4)) format = landscape(A4) num_pages = len(images) for filename in images: image = ImageReader(filename) img_w, img_h = image.getSize() avail_w = format[0] - 2 * args.margin_x * cm avail_h = format[1] - 2 * args.margin_y * cm scale = min(avail_w / img_w, avail_h / img_h) target_w = img_w * scale target_h = img_h * scale target_x = args.margin_x * cm + (0 if args.no_center else (avail_w - target_w) / 2) target_y = args.margin_y * cm + (0 if args.no_center else (avail_h - target_h) / 2) c.drawImage(image, target_x, target_y, target_w, target_h) page_num = c.getPageNumber() if not args.no_footer: text = str(page_num) if args.no_total else '{0} / {1:d}'.format( page_num, num_pages) c.drawCentredString(A4[0] / 2, footer_y, text) c.showPage() print('Processed {} - page {}'.format(filename, page_num)) c.save() if sys.platform.startswith('linux'): os.system('xdg-open "%s"' % args.output) else: os.system('start "" "%s"' % args.output)
def _image(self, node): #add attribute 'src' to tag 'image' by xiandong.xie s = StringIO.StringIO() if node.hasAttribute('src'): import base64 imgdata = base64.b64decode(node.getAttribute('src')) s.write(imgdata) else: import urllib u = urllib.urlopen(str(node.getAttribute('file'))) s.write(u.read()) from reportlab.lib.utils import ImageReader s.seek(0) img = ImageReader(s) (sx,sy) = img.getSize() args = {} for tag in ('width','height','x','y'): if node.hasAttribute(tag): args[tag] = utils.unit_get(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width'])/args['height'])>(float(sx)>sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def convertPDF(chapter_num, series_name): try: n = 1 for dirpath, dirnames, filenames in os.walk("ROOT_PATH"): PdfOutputFileName = "chapter" + str(chapter_num) + ".pdf" c = canvas.Canvas(PdfOutputFileName) if n == 1: filenames = sorted([name for name in filenames if name.endswith(".jpg")], key=pageNum) for filename in filenames: print "evaluating file name " + filename LowerCaseFileName = filename.lower() if LowerCaseFileName.endswith(".jpg"): filepath = os.path.join(dirpath, filename) print "found page " + filename im = ImageReader(filepath) imagesize = im.getSize() c.setPageSize(imagesize) c.drawImage(filepath, 0, 0) c.showPage() c.save() try: os.remove(filepath) except WindowsError as e: print e n = n + 1 print "PDF created " + PdfOutputFileName except: raise
def draw(self, canv, value): img = ImageReader(value) img_w, img_h = img.getSize() #crop by min side if self.w > self.h: k = self.h / img_h else: k = self.w / img_w width = img_w * k height = img_h * k #center align cx = self.w / 2 - width / 2 cy = self.h / 2 - height / 2 canv.drawImage(img, self.x + cx, self.y + cy, width, height, mask='auto') #debug canv.setStrokeColor(green) canv.roundRect(self.x, self.y, self.w, self.h, 4, stroke=1, fill=0) return canv
def _create_header(canvas, doc, draw_page_number=True): canvas.saveState() canvas.setTitle('Invoice') canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y = PAGE_HEIGHT - HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, PAGE_WIDTH / 3, current_y - (dpaw_header_logo_size[1]/2),width=dpaw_header_logo_size[0]/2, height=dpaw_header_logo_size[1]/2, mask='auto') current_y -= 70 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'TAX INVOICE') current_y -= 20 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'ABN: 38 052 249 024') # Invoice address details invoice_details_offset = 37 current_y -= 10 invoice = doc.invoice proposal = doc.proposal #bi = proposal.bookings.filter(invoices__invoice_reference=invoice.reference) # TODO need to fix, since individual parks can be exempt, Below calculation assumes NO PARK IS exempt #is_gst_exempt = proposal.application_type.is_gst_exempt if proposal.fee_invoice_reference == invoice.reference else False canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) current_x = PAGE_MARGIN + 5 if proposal.org_applicant: canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), proposal.applicant) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,invoice.owner.get_full_name()) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,invoice.owner.email) current_x += 435 #write Invoice details canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),'Date') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), to_local_tz(invoice.created).strftime(DATE_FORMAT) + ' (AWST)' ) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Page') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, str(canvas.getPageNumber())) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Proposal Number') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, proposal.lodgement_number) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Invoice Number') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, invoice.reference) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Total (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, currency(invoice.amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, 'GST included (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, currency(invoice.amount - calculate_excl_gst(invoice.amount) if not _is_gst_exempt(proposal, invoice) else 0.0)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, 'Paid (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, currency(invoice.payment_amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 8, 'Outstanding (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 8, currency(invoice.balance)) # if bi and bi[0].deferred_payment_date and invoice.payment_method in [invoice.PAYMENT_METHOD_MONTHLY_INVOICING, invoice.PAYMENT_METHOD_BPAY]: # canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 9, 'Payment Due Date') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 9, bi[0].deferred_payment_date.strftime(DATE_FORMAT)) canvas.restoreState()
def get_image(path, width): """ Get image to diplay on pdf at original aspect ratio """ img = ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) return Image(path, width=width, height=(width * aspect))
def test(self): from reportlab.lib.testutils import testsFolder from reportlab.lib.utils import rl_isfile imageFileName = os.path.join(testsFolder, 'pythonpowered.gif') assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110, 44) pixels = ir.getRGBData() assert md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def _create_header(canvas, doc, draw_page_number=True): canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y = PAGE_HEIGHT - HEADER_MARGIN canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'DEPARTMENT OF PARKS AND WILDLIFE') current_y -= 30 dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, HEADER_MARGIN, current_y - dpaw_header_logo_size[1]) current_x = HEADER_MARGIN + dpaw_header_logo_size[0] + 5 canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), 'Enquiries:') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Telephone:') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Facsimile:') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Web Site:') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Correspondance:') current_x += 80 canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), '17 DICK PERRY AVE, KENSINGTON, WESTERN AUSTRALIA') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, '08 9219 9000') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, '08 9219 8242') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, doc.site_url) canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Locked Bag 30') canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, 'Bentley Delivery Centre WA 6983') canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y -= 36 current_x += 200 if draw_page_number: canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER), 'PAGE') if hasattr(doc, 'licence') and doc.licence.licence_number is not None and doc.licence.licence_sequence: canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'NO.') canvas.setFont(DEFAULT_FONTNAME, LARGE_FONTSIZE) current_x += 50 if draw_page_number: canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER), str(canvas.getPageNumber())) if hasattr(doc, 'licence') and doc.licence.licence_number is not None and doc.licence.licence_sequence: canvas.drawString(current_x, current_y - (LARGE_FONTSIZE + HEADER_SMALL_BUFFER) * 2, '%s-%d' % (doc.licence.licence_number, doc.licence.licence_sequence))
def test(self): from reportlab.lib.testutils import testsFolder from reportlab.lib.utils import rl_isfile imageFileName = os.path.join(testsFolder,'pythonpowered.gif') assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110,44) pixels = ir.getRGBData() assert md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def test(self): import reportlab.test from reportlab.lib.utils import rl_isfile imageFileName = os.path.dirname(reportlab.test.__file__) + os.sep + 'pythonpowered.gif' assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110,44) pixels = ir.getRGBData() assert md5.md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def generate_pdf(chapter_name, images, out_file_path): canvas = Canvas(out_file_path) canvas.setTitle(chapter_name) for img_url in images: print 'downloading image: ', img_url image = ImageReader(img_url) canvas.setPageSize(image.getSize()) canvas.drawImage(image, x=0, y=0) canvas.showPage() canvas.save()
def draw_logo(self, x, y, width, height): if self.logo_url is None: return print(f"WTF {self.logo_url}") logo = ImageReader(self.logo_url) if logo.getSize()[0] > 2000: # Discount König Resize ... width += 40 height += 40 x -= 43 self.drawImage(logo, x, y, width=width, height=height)
def test(self): import reportlab.test from reportlab.lib.utils import rl_isfile imageFileName = os.path.dirname(reportlab.test.__file__) + os.sep + 'pythonpowered.gif' assert rl_isfile(imageFileName), "%s not found!" % imageFileName ir = ImageReader(imageFileName) assert ir.getSize() == (110,44) pixels = ir.getRGBData() assert md5.md5(pixels).hexdigest() == '02e000bf3ffcefe9fc9660c95d7e27cf'
def __payment_line(self): canvas = self.canv current_y, current_x = self.current_y, self.current_x bpay_logo = ImageReader(BPAY_LOGO) # Pay By Cheque cheque_x = current_x + 4 * inch cheque_y = current_y - 10 if self.invoice.payment_method in [ self.invoice.PAYMENT_METHOD_MONTHLY_INVOICING, self.invoice.PAYMENT_METHOD_BPAY ]: # Outer BPAY Box canvas.rect(current_x, current_y - 25, 2.3 * inch, -1.2 * inch) canvas.setFillColorCMYK(0.8829, 0.6126, 0.0000, 0.5647) # Move into bpay box current_y += 5 box_pos = current_x + 0.1 * inch bpay_logo_size = bpay_logo.getSize() canvas.drawImage(bpay_logo, box_pos, current_y - (bpay_logo_size[1] / 12 * 1.7), height=bpay_logo_size[1] / 12, width=bpay_logo_size[0] / 12, mask='auto') # Create biller information box biller_x = box_pos + bpay_logo_size[0] / 12 + 1 canvas.rect(biller_x, (current_y - (bpay_logo_size[1] / 12 * 1.7)) + 3, 1.65 * inch, (bpay_logo_size[1] / 12) - 5) # Bpay info canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) info_y = ((current_y - (bpay_logo_size[1] / 12 * 1.7)) + 3) + (0.35 * inch) canvas.drawString( biller_x + 5, info_y, 'Biller Code: {}'.format(self.invoice.biller_code)) canvas.drawString(biller_x + 5, info_y - 20, 'Ref: {}'.format(self.invoice.reference)) # Bpay Info string canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) canvas.drawString(box_pos, info_y - 0.55 * inch, 'Telephone & Internet Banking - BPAY') canvas.setFont(DEFAULT_FONTNAME, 6.5) canvas.drawString( box_pos, info_y - 0.65 * inch, 'Contact your bank or financial institution to make') canvas.drawString( box_pos, info_y - 0.75 * inch, 'this payment from your cheque, savings, debit or') canvas.drawString( box_pos, info_y - 0.85 * inch, 'transaction account. More info: www.bpay.com.au') self.current_y = current_y
def __init__(self,name,column,path,width=None,height=None): super().__init__(name,column) img = ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) if width is None: width = aspect*2 if height is None: height=(width * aspect) self.platypus_object = Image(path, width=width, height=height, hAlign='LEFT')
def pdf(self,REQUEST): """ Test """ skin = self.portal_skins.invoicing_templates showTemplate=skin.showIssue output = StringIO() c = canvas.Canvas(output,pagesize=letter,bottomup=0) x=35 y=50 theImage=self.getPicture() theImageData = StringIO() theImageUsage = theImage.file._read_data(theImageData) theImageReader = ImageReader(theImageUsage) (width,height) = theImageReader.getSize() parent = self.aq_inner.aq_parent width = self.getWidth() height = self.getHeight() if self.getTopMargin(): y+=15 c.drawImage(theImageReader,x,y,width,height,anchor='ne') caption = self.getCaption() credit = self.getCredit() pdfmetrics.registerFont(TTFont('FilosBold','FilosBol.ttf')) pdfmetrics.registerFont(TTFont('FilosReg','FilosReg.ttf')) if caption is not None: textobject = c.beginText() h = self.getHeight() if h is None: h = 400 textobject.setTextOrigin(x,y+h+30) fontsize = 14 textobject.setFont("FilosReg", fontsize) textobject.textLine(caption) c.drawText(textobject) if credit is not None: textobject = c.beginText() h = self.getHeight() if h is None: h = 400 w = self.getWidth() w = w - 100 textobject.setTextOrigin(x-w,y+h+15) fontsize = 11 textobject.setFont("FilosReg",fontsize) textobject.textLine(credit) c.drawText(textobject) c.showPage() c.save() result = output.getvalue() output.close() response = REQUEST.RESPONSE response.setHeader('Content-type','application/pdf') return result
def get_image(image, max_width, max_height): im = ImageReader(image) w, h = im.getSize() ratio = h / w if (w > max_width) or (h > max_height): if ratio > 1: return Image(image, width=max_height / ratio, height=max_height) else: return Image(image, width=max_width, height=max_weight * ratio) else: return Image(image)
def get_image(self, game, path, width=1*cm, height=None): """ Create an image from a path - either on on disc or from a web URL. """ if self.progress: print "Retrieving image for game: %7d" % int(game.id) img = ImageReader(path) iw, ih = img.getSize() aspect = ih / float(iw) if height: return Image(path, width=(height * aspect), height=height) else: return Image(path, width=width, height=(width * aspect))
def image(self, filename, width=None, height=None, left=0, bottom=0, top=None, right=None, mask=None, preserveAspectRatio=False, anchor='c'): ''' add an image to canvas ''' self.saveState() image = ImageReader(filename) width = image.getSize()[0] if width==None else width height = image.getSize()[1] if height==None else height width = checkPercent(width, self.width) height = checkPercent(height, self.height) x, y = self.placement(width, height, left, bottom, top, right) self.drawImage(image, x, y, width, height, mask, preserveAspectRatio, anchor) self.restoreState()
class ImageInline(platypus.Flowable): def __init__(self, img, width=-1, height=-1): platypus.Flowable.__init__(self) if img: imgdata = base64.decodestring(img) imgfile = cStringIO.StringIO(imgdata) self.img = ImageReader(imgfile) self.width, self.height = self.img.getSize() else: self.img = False def draw(self): if self.img: self.canv.drawImage(self.img, 0, 0, self.width, self.height)
def scale_image(image: str, desire_width: int) -> Image: """ Menginputkan path image dan width dan mengembalikan scaled image """ img_qr_code = ImageReader(image) img_width, img_height = img_qr_code.getSize() aspect = img_height / float(img_width) img_qr_code = Image(image, width=desire_width, height=(desire_width * aspect), hAlign='CENTER') return img_qr_code
def draw_cards_images(c, images, card, sizes, diameter, margin, x, y): """Function called to draw a card's images.""" # randomly choose sizes of images s = random.choices(sizes, k=len(card)) s = sorted(s, reverse=True) # create circles packed in circle circles = circ.circlify(s) for i, circle in zip(card, circles): # calculate the center and diameter of a circle cx = margin + (circle.x + 1) / 2 * (diameter - 2 * margin) cy = margin + (circle.y + 1) / 2 * (diameter - 2 * margin) r = circle.r * (diameter - 2 * margin) / 2 * 0.9 # leave some space between circles # # draw a circle around the image # def draw_circles(): # drawing = Drawing(diameter, diameter) # circle = Circle(cx, cy, r, fillColor=colors.white) # drawing.add(circle) # return drawing # renderPDF.draw(draw_circles(), c, x, y) # generate a random angle angle = random.randint(0, 359) c.saveState() # move the canvas origin to the image's position c.translate(x + cx, y + cy) # and rotate it by random angle c.rotate(angle) # draw the image img = ImageReader(images[i]) width, height = img.getSize() phi = math.atan(height / width) a = 2 * r * math.cos(phi) b = 2 * r * math.sin(phi) c.drawImage(img, -a / 2, -b / 2, a, b, 'auto') c.restoreState() return c
class PDF_receipt(object): def __init__(self, facName, size): self.papersize = self.milimetersToPoints(*size) #A4 (148, 210) self.border = self.milimetersToPoints(5, 10) self.logo = ImageReader("Logo.jpg") size = self.logo.getSize() factor = size[Y] / size[X] self.logoWidth = self.papersize[X] - 4 * self.border[X] self.logoHeight = self.logoWidth * factor self.canvas = canvas.Canvas(facName, self.papersize) self.header(self.border[X], self.papersize[Y]) self.footer('¡Gracias por su compra, Vuelva pronto!') self.canvas.setFont("Courier", 12) self.canvas.setFillColor("black") def milimetersToPoints(self, width, height): width = (0.0393701 * width) / (1 / 72) height = 0.0393701 * height / (1 / 72) return width, height def insertText(self, x, y, texto): text = self.canvas.beginText(x, y) for row in texto: text.textLine(row) self.canvas.drawText(text) def header(self, x, y): spaceTocenter = (self.papersize[X] - 2 * self.border[X] - self.logoWidth) / 2 self.canvas.drawImage(self.logo, x + spaceTocenter, y - self.logoHeight - self.border[Y],\ width = self.logoWidth , height = self.logoHeight) def footer(self, message): self.canvas.setFont("Courier-Bold", 15) self.canvas.setFillColorRGB(0.929, .49, 0.192) self.canvas.drawString(2.5 * self.border[X], self.border[Y], message) def end(self): self.canvas.showPage() self.canvas.save()
def createPDF(pdfname, files): '''Create PDF file from a list. pdfname: a string path for the PDF file. files: a list with each element containing a string path for an image file.''' pdf = canvas.Canvas(pdfname) i = 1 for file in files: img = ImageReader(file) pdf.setPageSize(img.getSize()) try: pdf.drawImage(img, 0, 0) except OSError: pdf.drawImage(file, 0, 0) pdf.showPage() print('{}: {}'.format(i, os.path.basename(file))) i += 1 pdf.save()
def callPDFPDTBySameName(self,c,x,y,REQUEST,parent,top,pagenumber): """ Test """ y = 1200 - y self.left = x self.top = y print self.Title() self.pagenumber=pagenumber skinTool = getToolByName(self, 'portal_skins') items = self.listFolderContents(contentFilter={"portal_type":"Advertizement"}) for ad in items: theImage = ad.getImage() thePress = ImageReader(StringIO(str(theImage.data))) (width,height) = thePress.getSize() c.drawImage(thePress,x,y,width,height) return (x,y)
def _image(self, node): import urllib from reportlab.lib.utils import ImageReader if not node.get('file'): if node.get('name'): image_data = self.images[node.get('name')] s = cStringIO.StringIO(image_data) else: import base64 if self.localcontext: res = utils._regex.findall(node.text) for key in res: newtext = eval(key, {}, self.localcontext) node.text = newtext image_data = base64.decodestring(node.text) if not image_data: return False s = cStringIO.StringIO(image_data) else: if node.get('file') in self.images: s = cStringIO.StringIO(self.images[node.get('file')]) else: try: u = urllib.urlopen(str(node.get('file'))) s = cStringIO.StringIO(u.read()) except Exception: u = file(os.path.join(self.path, str(node.get('file'))), 'rb') s = cStringIO.StringIO(u.read()) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.get(tag): args[tag] = utils.unit_get(node.get(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width']) / args['height']) > (float(sx) > sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def __payment_line(self): canvas = self.canv current_y, current_x = self.current_y, self.current_x bpay_logo = ImageReader(BPAY_LOGO) #current_y -= 40 # Pay By Cheque cheque_x = current_x + 4 * inch cheque_y = current_y -30 canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) canvas.drawString(cheque_x, cheque_y, 'Pay By Cheque:') canvas.setFont(DEFAULT_FONTNAME, 9) cheque_y -= 15 canvas.drawString(cheque_x, cheque_y, 'Make cheque payable to: Department of Biodiversity, Conservation and Attractions') cheque_y -= 15 canvas.drawString(cheque_x, cheque_y, 'Mail to: Department of Biodiversity, Conservation and Attractions') cheque_y -= 15 canvas.drawString(cheque_x + 32, cheque_y, 'Locked Bag 30') cheque_y -= 15 canvas.drawString(cheque_x + 32, cheque_y, 'Bentley Delivery Centre WA 6983') if settings.BPAY_ALLOWED: # Outer BPAY Box canvas.rect(current_x,current_y - 25,2.3*inch,-1.2*inch) canvas.setFillColorCMYK(0.8829,0.6126,0.0000,0.5647) # Move into bpay box current_y += 5 box_pos = current_x + 0.1 * inch bpay_logo_size = bpay_logo.getSize() canvas.drawImage(bpay_logo, box_pos, current_y - (bpay_logo_size[1]/12 * 1.7), height= bpay_logo_size[1]/12,width=bpay_logo_size[0]/12, mask='auto') # Create biller information box biller_x = box_pos + bpay_logo_size[0]/12 + 1 canvas.rect(biller_x,(current_y - (bpay_logo_size[1]/12 * 1.7)) + 3,1.65*inch,(bpay_logo_size[1]/12)-5) # Bpay info canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) info_y = ((current_y - (bpay_logo_size[1]/12 * 1.7)) + 3) + (0.35 * inch) canvas.drawString(biller_x + 5, info_y, 'Biller Code: {}'.format(self.invoice.biller_code)) canvas.drawString(biller_x + 5, info_y - 20, 'Ref: {}'.format(self.invoice.reference)) # Bpay Info string canvas.setFont(BOLD_FONTNAME,SMALL_FONTSIZE) canvas.drawString(box_pos, info_y - 0.55 * inch, 'Telephone & Internet Banking - BPAY') canvas.setFont(DEFAULT_FONTNAME,6.5) canvas.drawString(box_pos, info_y - 0.65 * inch, 'Contact your bank or financial institution to make') canvas.drawString(box_pos, info_y - 0.75 * inch, 'this payment from your cheque, savings, debit or') canvas.drawString(box_pos, info_y - 0.85 * inch, 'transaction account. More info: www.bpay.com.au') self.current_y = current_y
def __payment_line(self): canvas = self.canv current_y, current_x = self.current_y, self.current_x bpay_logo = ImageReader(BPAY_LOGO) #current_y -= 40 # Pay By Cheque cheque_x = current_x + 4 * inch cheque_y = current_y -30 canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) canvas.drawString(cheque_x, cheque_y, 'Pay By Cheque:') canvas.setFont(DEFAULT_FONTNAME, 9) cheque_y -= 15 canvas.drawString(cheque_x, cheque_y, 'Make cheque payable to: Department of Parks and Wildlife') cheque_y -= 15 canvas.drawString(cheque_x, cheque_y, 'Mail to: Department of Parks and Wildlife') cheque_y -= 15 canvas.drawString(cheque_x + 32, cheque_y, 'Locked Bag 30') cheque_y -= 15 canvas.drawString(cheque_x + 32, cheque_y, 'Bentley Delivery Centre WA 6983') if settings.BPAY_ALLOWED: # Outer BPAY Box canvas.rect(current_x,current_y - 25,2.3*inch,-1.2*inch) canvas.setFillColorCMYK(0.8829,0.6126,0.0000,0.5647) # Move into bpay box current_y += 5 box_pos = current_x + 0.1 * inch bpay_logo_size = bpay_logo.getSize() canvas.drawImage(bpay_logo, box_pos, current_y - (bpay_logo_size[1]/12 * 1.7), height= bpay_logo_size[1]/12,width=bpay_logo_size[0]/12, mask='auto') # Create biller information box biller_x = box_pos + bpay_logo_size[0]/12 + 1 canvas.rect(biller_x,(current_y - (bpay_logo_size[1]/12 * 1.7)) + 3,1.65*inch,(bpay_logo_size[1]/12)-5) # Bpay info canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) info_y = ((current_y - (bpay_logo_size[1]/12 * 1.7)) + 3) + (0.35 * inch) canvas.drawString(biller_x + 5, info_y, 'Biller Code: {}'.format(self.invoice.biller_code)) canvas.drawString(biller_x + 5, info_y - 20, 'Ref: {}'.format(self.invoice.reference)) # Bpay Info string canvas.setFont(BOLD_FONTNAME,SMALL_FONTSIZE) canvas.drawString(box_pos, info_y - 0.55 * inch, 'Telephone & Internet Banking - BPAY') canvas.setFont(DEFAULT_FONTNAME,6.5) canvas.drawString(box_pos, info_y - 0.65 * inch, 'Contact your bank or financial institution to make') canvas.drawString(box_pos, info_y - 0.75 * inch, 'this payment from your cheque, savings, debit or') canvas.drawString(box_pos, info_y - 0.85 * inch, 'transaction account. More info: www.bpay.com.au') self.current_y = current_y
def _image(self, node): import urllib from reportlab.lib.utils import ImageReader if not node.get('file') : if node.get('name'): image_data = self.images[node.get('name')] s = cStringIO.StringIO(image_data) else: import base64 if self.localcontext: res = utils._regex.findall(node.text) for key in res: newtext = eval(key, {}, self.localcontext) node.text = newtext image_data = base64.decodestring(node.text) if not image_data: return False s = cStringIO.StringIO(image_data) else: if node.get('file') in self.images: s = cStringIO.StringIO(self.images[node.get('file')]) else: try: u = urllib.urlopen(str(node.get('file'))) s = cStringIO.StringIO(u.read()) except Exception: u = file(os.path.join(self.path,str(node.get('file'))), 'rb') s = cStringIO.StringIO(u.read()) img = ImageReader(s) (sx,sy) = img.getSize() args = {} for tag in ('width','height','x','y'): if node.get(tag): args[tag] = utils.unit_get(node.get(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width'])/args['height'])>(float(sx)>sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx self.canvas.drawImage(img, **args)
def _create_header(canvas, doc, draw_page_number=True): canvas.saveState() canvas.setTitle('Invoice') canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y = PAGE_HEIGHT - HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, PAGE_WIDTH / 3, current_y - (dpaw_header_logo_size[1]/2),width=dpaw_header_logo_size[0]/2, height=dpaw_header_logo_size[1]/2, mask='auto') current_y -= 70 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'INFRINGEMENT NOTICE') current_y -= 20 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'ABN: 38 052 249 024') # Invoice address details invoice_details_offset = 37 current_y -= 20 # invoice = doc.invoice sanction_outcome = doc.sanction_outcome canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) current_x = PAGE_MARGIN + 5 canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), sanction_outcome.get_offender()[0].get_full_name()) # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), invoice.owner.get_full_name()) # canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,invoice.owner.username) current_x += 452 #write Invoice details canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),'Date') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),invoice.created.strftime(DATE_FORMAT)) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Page') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, str(canvas.getPageNumber())) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Invoice Number') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, invoice.reference) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Total (AUD)') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, currency(invoice.amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'GST included (AUD)') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, currency(invoice.amount - calculate_excl_gst(invoice.amount))) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, 'Paid (AUD)') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, currency(invoice.payment_amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, 'Outstanding (AUD)') # canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, currency(invoice.balance)) canvas.restoreState()
def _create_header(canvas, doc, draw_page_number=True): canvas.saveState() canvas.setTitle('Invoice') canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y = PAGE_HEIGHT - HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, PAGE_WIDTH / 3, current_y - (dpaw_header_logo_size[1]/2),width=dpaw_header_logo_size[0]/2, height=dpaw_header_logo_size[1]/2, mask='auto') current_y -= 70 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'TAX INVOICE') current_y -= 20 canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, 'ABN: 38 052 249 024') # Invoice address details invoice_details_offset = 37 current_y -= 20 invoice = doc.invoice canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) current_x = PAGE_MARGIN + 5 canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),invoice.owner.get_full_name()) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,invoice.owner.username) current_x += 452 #write Invoice details canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),'Date') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),invoice.created.strftime(DATE_FORMAT)) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Page') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, str(canvas.getPageNumber())) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Invoice Number') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, invoice.reference) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Total (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, currency(invoice.amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'GST included (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, currency(invoice.amount - calculate_excl_gst(invoice.amount))) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, 'Paid (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 6, currency(invoice.payment_amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, 'Outstanding (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 7, currency(invoice.balance)) canvas.restoreState()
def generate_pdf(chapter_name, images_dir, out_file_path): canvas = Canvas(out_file_path) canvas.setTitle(chapter_name) print("Generating PDF", end="", flush=True) for file in os.listdir(images_dir): if os.path.isdir(file) or not isImage(file): continue image = ImageReader(images_dir + "/" + file) canvas.setPageSize(image.getSize()) canvas.drawImage(image, x=0, y=0) canvas.showPage() print(".", end="", flush=True) print("", flush=True) canvas.save()
def Merge(self): c = canvas.Canvas(self.outputPath) for pn in range(1, len(os.listdir(self.__chWork.downloadDir)) + 1): try: fn = os.path.join(self.__chWork.downloadDir, str(pn)+".png") # fn = self.__chWork.downloadDir+"\\"+str(pn)+".png" im = ImageReader(fn) imageSize = im.getSize() c.setPageSize(imageSize) c.drawImage(fn, 0, 0) c.showPage() sys.stdout.write(time.asctime(time.localtime(time.time()))+" : "+fn+"has been merged into PDF: "+self.outputPath+"\n") except: # TODO excetion handling sys.stdout.write(time.asctime(time.localtime(time.time()))+" : "+"merge failure!\n") c.save() sys.stdout.write(time.asctime(time.localtime(time.time()))+" : "+self.outputPath+" is done.\n") self.tasker.PutIntoPusherQueue(self.__chWork) return
def _create_header(canvas, doc, draw_page_number=True): canvas.saveState() canvas.setTitle('Confirmation') canvas.setFont(BOLD_FONTNAME, LARGE_FONTSIZE) current_y = PAGE_HEIGHT - HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, PAGE_WIDTH / 3, current_y - (dpaw_header_logo_size[1]/2),width=dpaw_header_logo_size[0]/2, height=dpaw_header_logo_size[1]/2, mask='auto') current_y -= 70 invoice = doc.invoice application_fee = doc.application_fee PAGE_TITLE = 'APPLICATION CONFIRMATION' canvas.drawCentredString(PAGE_WIDTH / 2, current_y - LARGE_FONTSIZE, PAGE_TITLE) # Invoice address details invoice_details_offset = 37 current_y -= 25 canvas.setFont(BOLD_FONTNAME, SMALL_FONTSIZE) current_x = PAGE_MARGIN + 5 if application_fee.proposal.applicant and hasattr(application_fee.proposal.applicant, 'name'): canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), application_fee.proposal.applicant.name) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2,invoice.owner.get_full_name()) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3,invoice.owner.email) current_x += 435 #write Invoice details canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER),'Date') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER), to_local_tz(invoice.created).strftime(DATE_FORMAT) + ' (AWST)' ) canvas.drawString(current_x, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, 'Page') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 2, str(canvas.getPageNumber())) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, 'Invoice Number') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 3, invoice.reference) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, 'Paid (AUD)') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 4, currency(invoice.payment_amount)) canvas.drawRightString(current_x + 20, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, 'Proposal Lodgement No.') canvas.drawString(current_x + invoice_details_offset, current_y - (SMALL_FONTSIZE + HEADER_SMALL_BUFFER) * 5, application_fee.proposal.lodgement_number) canvas.restoreState()
def save_book(self, book_id): base_dir = os.path.dirname(os.path.dirname(__file__)) tmp_dir = base_dir + '/tmp' pdf_path = base_dir + '/book_' + str(book_id) + '.pdf' c = canvas.Canvas(pdf_path) page = 0 if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) while True: img_path = base_dir + '/tmp/image_' + str(page) + '.jpg' response = self.browser.get('http://elibrary.misis.ru/plugins/SecView/getDoc.php?id='+ str(book_id) +'&page='+ str(page) +'&type=large/fast', stream=True) #quit if it isn't an image if not response.headers['content-type'] == 'image/jpeg': break #save image with open(img_path, 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response #add image to pdf im = ImageReader(img_path) imagesize = im.getSize() c.setPageSize(imagesize) c.drawImage(img_path,0,0) c.showPage() c.save() #remove image os.remove(img_path) page += 1 #remove tmp folder os.rmdir(tmp_dir)
def cacheImageFile(filename, returnInMemory=0, IMG=None): "Processes image as if for encoding, saves to a file with .a85 extension." from reportlab.lib.utils import open_for_read import zlib cachedname = os.path.splitext(filename)[0] + '.a85' if filename==cachedname: if cachedImageExists(filename): if returnInMemory: return split(open_for_read(cachedname).read(),LINEEND)[:-1] else: raise IOError, 'No such cached image %s' % filename else: img = ImageReader(filename) if IMG is not None: IMG.append(img) imgwidth, imgheight = img.getSize() raw = img.getRGBData() code = [] # this describes what is in the image itself code.append('BI') code.append('/W %s /H %s /BPC 8 /CS /RGB /F [/A85 /Fl]' % (imgwidth, imgheight)) code.append('ID') #use a flate filter and Ascii Base 85 assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) #this bit is very fast... encoded = _AsciiBase85Encode(compressed) #...sadly this may not be #append in blocks of 60 characters _chunker(encoded,code) code.append('EI') if returnInMemory: return code #save it to a file f = open(cachedname,'wb') f.write(join(code, LINEEND)+LINEEND) f.close() if rl_config.verbose: print 'cached image as %s' % cachedname
def print_logo(self): """ Print the company logo on the current page The logo can not be added through the xsl template because we use a NumberedCanvas. When using this type of canevas, the images on the template are ignored. """ logo_data = base64.decodestring( self.localcontext['company_logo'] or '') s = StringIO(logo_data) img = ImageReader(s) (sx, sy) = img.getSize() args = { 'x': 1.3 * cm, 'y': 18.8 * cm, 'mask': 'auto', 'height': 40.0, 'width': 40.0 * sx / sy, } self.drawImage(img, **args) s.close()
def __logo_line(self): canvas = self.canv current_y, current_x = self.current_y, self.current_x canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO_SM) dpaw_header_logo_size = dpaw_header_logo.getSize() canvas.drawImage(dpaw_header_logo, HEADER_MARGIN, current_y - (dpaw_header_logo_size[1]/1.8),height=dpaw_header_logo_size[1]/1.8, mask='auto', width=dpaw_header_logo_size[0]/1.8) current_y = -20 canvas.setFont(BOLD_FONTNAME, MEDIUM_FONTSIZE) canvas.drawRightString(current_x * 45,current_y,'Remittance Advice') current_y -= 20 canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) canvas.drawString(current_x * 27,current_y,'PLEASE DETACH AND RETURN WITH YOUR PAYMENT') current_y -= 20 canvas.setFont(DEFAULT_FONTNAME, MEDIUM_FONTSIZE) canvas.drawString(current_x, current_y, 'ABN: 38 052 249 024') self.current_y = current_y
def default_image_resolver(node): import urllib from reportlab.lib.utils import ImageReader u = urllib.urlopen(str(node.getAttribute('file'))) s = StringIO.StringIO() s.write(u.read()) s.seek(0) img = ImageReader(s) (sx, sy) = img.getSize() args = {} for tag in ('width', 'height', 'x', 'y'): if node.hasAttribute(tag): args[tag] = utils.as_pt(node.getAttribute(tag)) if ('width' in args) and (not 'height' in args): args['height'] = sy * args['width'] / sx elif ('height' in args) and (not 'width' in args): args['width'] = sx * args['height'] / sy elif ('width' in args) and ('height' in args): if (float(args['width'])/args['height'])>(float(sx)>sy): args['width'] = sx * args['height'] / sy else: args['height'] = sy * args['width'] / sx return img, args
class Image(SimpleChunk): """An image.""" def __init__(self, filename, zoom=100, raised_by=0): self.filename = filename self.zoom = zoom self.raised_by = 0 self.image = ImageReader(filename) def size(self, canvas, w, h): myw, myh = self.image.getSize() myw = myw * self.zoom / 100 myh = myh * self.zoom / 100 return myw, myh def drawOn(self, canvas, x, y, w, h): myw, myh = self.size(canvas, w, h) canvas.drawImage(self.filename, x, y - myh + self.raised_by, myw, myh, mask='auto') return x + myw, y def __str__(self): return '[%s]' % self.filename