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 _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 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 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 _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 _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 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 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 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 _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 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 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 draw_image(self, image, alpha_channel=None): if not image: return if self.colorspace == uc2const.COLOR_CMYK: image = self.cms.convert_image(image, uc2const.IMAGE_CMYK) elif self.colorspace == uc2const.COLOR_RGB: image = self.cms.convert_image(image, uc2const.IMAGE_RGB) elif self.colorspace == uc2const.COLOR_GRAY: image = self.cms.convert_image(image, uc2const.IMAGE_GRAY) img = ImageReader(image) img.getRGBData() if alpha_channel: img._dataA = ImageReader(alpha_channel) self.canvas.drawImage(img, 0, 0, mask='auto')
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 __init__(self, fileName,ident=None): # check if the file is remote, if so, download it to a temporary file and reset fileName self._isRemote = _getIsRemote(fileName) if self._isRemote: fileName, self._format = _getRemoteFile(fileName) else: self._format = _getFormat(fileName) if self._format != 'jpg': raise IllegalFormat(fileName, 'JPG') ImageReader.__init__(self, fileName, ident)
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()
def create_diary_page(pdf_template, font, top_left_text, page_number, top_right_text): packet = BytesIO() diary_canvas = canvas.Canvas(packet, pagesize=A5) # Header diary_canvas.setFont(font, 11) #diary_canvas.drawRightString(378, 562, str(top_right_text)) diary_canvas.drawString(36.5, 562, top_left_text) # Corners corners = [(CORNER_DIR / Path("corner_ul.png"), 25, 553), (CORNER_DIR / Path("corner_ur.png"), 365, 553), (CORNER_DIR / Path("corner_bl.png"), 25, 15), (CORNER_DIR / Path("corner_br.png"), 365, 15)] for corner_path, x, y in corners: if corner_path.exists(): corner = ImageReader(corner_path) diary_canvas.drawImage(corner, x=x, y=y, mask='auto') # Footer #diary_canvas.setFont(font, 8) #diary_canvas.drawString(36.5, 24, str(page_number)) diary_canvas.save() # Merge template and additions (header, corners and footer) packet.seek(0) page_additions = PdfFileReader(packet).getPage(0) new_page = PdfFileReader(open(pdf_template, "rb")).getPage(0) new_page.mergePage(page_additions) new_page.scaleTo(A4[0], A4[1]) return new_page
def create_diary_cover(participant_id, email, font): '''Create cover of the A5 diary''' packet = BytesIO() cover_canvas = canvas.Canvas(packet, pagesize=A4) width, height = A4 # Centering the logo or participant ID if Path.exists(LOGO_PATH): logo = ImageReader(LOGO_PATH) cover_canvas.drawImage(logo, x=(width * (1 / 6.0)), y=(height / 4), width=width * (4 / 6.0), preserveAspectRatio=True, mask='auto') else: cover_canvas.setFont(font, 50) cover_canvas.drawCentredString(width / 2, height / 2, participant_id) # Lost legend if not (email is None or email == ""): cover_canvas.setFont(font, 15) cover_canvas.drawCentredString( width / 2, 50, "If you find this document, please email " + email) cover_canvas.save() packet.seek(0) return PdfFileReader(packet).getPage(0)
def imgs_to_pdf(img_path_list, target_path): """将一组图片合成一个pdf文件 :param str target_path: 输出pdf文件路径 :param list img_path_list: 要合成的图片的路径列表 :return str target_path: 输出pdf文件路径 """ a4_w, a4_h = portrait(A4) c = canvas.Canvas(target_path, pagesize=portrait(A4)) for img_path in img_path_list: img_w, img_h = ImageReader(img_path).getSize() if img_w / img_h > a4_w / a4_h: # 横图 ratio = a4_w / img_w left_margin = 0 top_margin = (a4_h - img_h * ratio) / 2 else: # 竖图 ratio = a4_h / img_h left_margin = (a4_w - img_w * ratio) / 2 top_margin = 0 c.drawImage(img_path, left_margin, top_margin, img_w * ratio, img_h * ratio) c.showPage() ensure_file_dir_exists(target_path) c.save() return target_path
def _draw_badge(self, canvas, registration, template, tpl_data, pos_x, pos_y): """Draw a badge for a given registration, at position pos_x, pos_y (top-left corner).""" config = self.config badge_rect = (pos_x, self.height - pos_y - tpl_data.height_cm * cm, tpl_data.width_cm * cm, tpl_data.height_cm * cm) if config.dashed_border: canvas.saveState() canvas.setDash(1, 5) canvas.rect(*badge_rect) canvas.restoreState() if template.background_image: with template.background_image.open() as f: self._draw_background(canvas, ImageReader(f), tpl_data, *badge_rect) placeholders = get_placeholders('designer-fields') for item in tpl_data.items: placeholder = placeholders.get(item['type']) if placeholder: if placeholder.group == 'registrant': text = placeholder.render(registration) else: text = placeholder.render(registration.event) elif item['text']: text = item['text'] self._draw_item(canvas, item, tpl_data, text, pos_x, pos_y)
def _create_letter_header_footer(canvas, doc): # header current_y = PAGE_HEIGHT - LETTER_HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) canvas.drawImage(dpaw_header_logo, LETTER_HEADER_MARGIN, current_y - LETTER_IMAGE_HEIGHT, width=LETTER_IMAGE_WIDTH, height=LETTER_IMAGE_HEIGHT)
def setPanelShotStatus(self, imageData): """ Sets the shots status of the given panel if status exists, aligned to the bottom left of the panel :param imageData: dictionary object with panel metaData """ panelX = imageData.get("panelX") panelY = imageData.get("panelY") if imageData.get('shotStatus'): statusIcon = [ status.iconPath for status in self.shotStatuses.statuses if imageData['shotStatus'] == status.label ] if len(statusIcon) > 0: statusIcon = statusIcon[0] if self.fileService.exists(statusIcon): if not statusIcon.endswith(('.jpg', '.jpeg')): statusIcon = statusIcon.replace( os.path.splitext(statusIcon)[-1], ".jpg") statusIconReader = ImageReader( self.repath.localize(statusIcon)) statusH = 15 statusW = statusH * (statusIconReader._width / float(statusIconReader._height)) statusX = panelX statusY = panelY - statusH - 2 self.canvas.drawImage(statusIconReader, statusX, statusY, statusW, statusH)
def convert_images_to_pdf(filenames, instructions=None, dpi=300): if instructions is None: instructions = [{} for _ in range(len(filenames))] a4_width, a4_height = A4 writer = io.BytesIO() pdf = canvas.Canvas(writer, pagesize=A4) for filename, instruction in zip(filenames, instructions): with Image(filename=filename, resolution=dpi) as image: image.background_color = Color('white') image.format = 'jpg' image.alpha_channel = 'remove' try: degree = instruction.get('rotate', 0) if degree and degree % 90 == 0: image.rotate(degree) except ValueError: pass if image.width > image.height: ratio = MAX_HEIGHT_A4 / image.width else: ratio = MAX_HEIGHT_A4 / image.height if ratio < 1: image.resize(round(ratio * image.width), round(ratio * image.height)) width = image.width * 72 / dpi height = image.height * 72 / dpi pdf.setPageSize((width, height)) reportlab_io_img = ImageReader(io.BytesIO(image.make_blob())) pdf.drawImage(reportlab_io_img, 0, 0, width=width, height=height) pdf.showPage() pdf.save() return writer.getvalue()
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 __page_header(self, canvas, doc): canvas.saveState() high=10.3 logo = ImageReader('{}/wcm_nyp_ClinicalGenomicsLab_Letterhead_CB_Opt01r.png'.format(path.dirname(path.realpath(__file__)))) logo_width, logo_height = self.__resize(logo, inch*0.75) canvas.drawImage(logo, inch*0.5, inch*10.1, width=logo_width, height=logo_height, mask='auto') canvas.setFont("Helvetica",14) canvas.drawString(inch*2.75, inch*(high-.4), 'Oncomine Comprehensive Report') canvas.setFont("Helvetica",8) canvas.drawString(inch*6.175, inch*10.6, 'Wayne Tam, MD, PhD - Director') canvas.drawString(inch*6.175, inch*10.5, 'Lab of Oncology-Molecular Detection') canvas.drawString(inch*6.175, inch*10.4, 'Weill Cornell Medicine') canvas.drawString(inch*6.175, inch*10.3, '1300 York Avenue K502, LC-904') canvas.drawString(inch*6.175, inch*10.2, 'New York, NY 10065') canvas.drawString(inch*6.175, inch*10.1, 'T:646.962.3816 F:212.746.8362') canvas.setFillColorRGB(255,0,0) canvas.setFillColorRGB(0,0,0) canvas.drawString(inch*7.5, inch*(0.4), 'Page {}'.format(doc.page)) canvas.line(inch/2, inch*(high-0.5), inch*8, inch*(high-0.5)) canvas.drawString(inch/2, inch*(high-0.4), "GX{}".format(self.sample_record['GX'])) canvas.restoreState()
def export_web_map(web_map_json): """Fetches the webmap and formats it to proper size to fit the PDF report""" #Implemented in MAP_ONLY Layout template output_path = os.path.join(arcpy.env.scratchFolder, "Webmap.png") #pylint: disable=E1101 web_map = convert(web_map_json) web_map_image = arcpy.ExportWebMap_server(str(web_map), output_path, Format="PNG32", Layout_Templates_Folder="", Layout_Template='MAP_ONLY') for img in os.listdir(arcpy.env.scratchFolder): #pylint: disable=E1101 if img.endswith(".png"): webmap = os.path.join(arcpy.env.scratchFolder, str(img)) #pylint: disable=E1101 break pil_image = PILImage.open(webmap) map_image_width, image_height = ImageReader(pil_image).getSize() reduce_by = 0.1 aspectratio = image_height / (float(map_image_width)) while (600 <= image_height or 500 <= map_image_width): map_image_width = map_image_width - reduce_by image_height = map_image_width * aspectratio reduce_by += 0.1 webmap_image_width = map_image_width webmap_image = Image(webmap, width=map_image_width, height=image_height) return webmap_image, webmap_image_width
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 _build_pdf(self, canvas): config = self.config tpl_data = self.tpl_data if self.template.background_image: with self.template.background_image.open() as f: self._draw_background( canvas, ImageReader(self._remove_transparency(f)), tpl_data, config.margin_horizontal, config.margin_vertical, tpl_data.width_cm * cm, tpl_data.height_cm * cm) placeholders = get_placeholders('designer-fields') for item in tpl_data.items: placeholder = placeholders.get(item['type']) if placeholder: if placeholder.group == 'event': text = placeholder.render(self.event) else: continue elif item.get('text') is not None: text = item['text'] self._draw_item(canvas, item, tpl_data, text, config.margin_horizontal, config.margin_vertical)
def footer(self, canvas, doc): footer_style = ParagraphStyle("footer_style", alignment=TA_CENTER, fontSize=7) footer_text = f"<br/><br/><br/> "\ f"<b>{self.client.contact.billing_address.firma} | {self.client.contact.billing_address.strasse} "\ f"{self.client.contact.billing_address.hausnummer} | {self.client.contact.billing_address.zip} "\ f"{self.client.contact.billing_address.place}</b><br/>"\ f"tel {self.client.contact.telefon} | fax {self.client.contact.fax} | " \ f"{self.client.contact.email} | {self.client.contact.website}"\ f"<br/>"\ f"{self.client.contact.bank.first().bank} | BIC: {self.client.contact.bank.first().bic} | "\ f"IBAN: {self.client.contact.bank.first().iban}"\ f"<br/>"\ f"{self.client.contact.commercial_register} | St.Nr. {self.client.contact.tax_number} | "\ f"Ust-IdNr. {self.client.contact.sales_tax_identification_number}"\ f"<br/>"\ if self.client.contact.billing_address.vorname and self.client.contact.billing_address.nachname: footer_text += f"Geschäftsführer: {self.client.contact.billing_address.vorname} " \ f"{self.client.contact.billing_address.nachname}" footer_text += f"<br/>" footer_paragraph = Paragraph(footer_text, footer_style) canvas.saveState() w, h = footer_paragraph.wrap(doc.width, doc.bottomMargin) footer_paragraph.drawOn(canvas, doc.leftMargin + 18, h - 70) if self.qr_code_url is not None: qr_code = ImageReader(self.qr_code_url) canvas.drawImage(qr_code, doc.leftMargin, h - 74, width=1 * inch, height=1 * inch) canvas.restoreState()
def add_proxy(self, image: t.Union[ImageReader, str, Image.Image]) -> None: self._canvas.drawImage( ImageReader(image) if isinstance(image, Image.Image) else image, self._cursor[0], self._cursor[1] - self._PROXY_HEIGHT, self._PROXY_WIDTH, self._PROXY_HEIGHT, mask = 'auto', ) if ( self._cursor[0] + (self._PROXY_WIDTH + self._card_margin_size) * 2 > self._page_size[0] - self._margin_size ): if ( self._cursor[1] - (self._PROXY_HEIGHT - self._card_margin_size) * 2 < self._margin_size ): self._canvas.showPage() self._reset_cursor() else: self._cursor = (self._margin_size, self._cursor[1] - self._PROXY_HEIGHT - self._card_margin_size) else: self._cursor = (self._cursor[0] + self._PROXY_WIDTH + self._card_margin_size, self._cursor[1])
def add_tail_page(canvas_param, pagesize=letter): """ 函数功能:为pdf文档添加功能,分“主题”、“副标题”两部分 :param canvas: :param pagesize: 页面大小,默认A4 :param theme: 主题字符串 :param subtitle: 副标题字符串 :return: """ PAGE_WIDTH = pagesize[0] PAGE_HEIGHT = pagesize[1] # 设置主标题字体并打印主标题 canvas_param.setFont("song", 20) canvas_param.drawString(20, PAGE_HEIGHT * 0.75, '联系我们:') canvas_param.drawString(20, PAGE_HEIGHT * 0.7, '魔灯量化(微信公众号)') # 插入小时macd图 image_file = PIL.Image.open(rootPath + 'Function\SeaSelect\Sub\modeng.jpg') canvas_param.drawImage(ImageReader(image_file), x=w * 0.3, y=h * 0.3, height=0.3 * h, width=0.4 * w, preserveAspectRatio=True) canvas_param.showPage() return canvas_param
def some_view(request, name, surname, description, photo): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') filename = name + "_" + surname + ".pdf" response['Content-Disposition'] = 'attachment; filename= "%s"' % filename buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # wczytywanie zdjęcia które zostaje niżej przekazane do narysowania na PDF'ie image = ImageReader(photo) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(30, 800, name + " " + surname) p.drawString(30, 770, description) p.drawImage(image, 10, 10, mask='auto') # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def watermarking(input_path: str, watermark_path: str, output_path: str): # Detecting if watermark is img or pdf if watermark_path.endswith('.pdf'): watermark = PdfFileReader(watermark_path).getPage(0) else: img = BytesIO() image_watermark = Image.open(watermark_path).convert('RGBA') new_data = transparency(image_watermark.getdata()) image_watermark.putdata(new_data) image_watermark.save(img, 'PNG') new_img = ImageReader(img) img_doc = BytesIO() new_canvas = canvas.Canvas(img_doc, pagesize=letter) new_canvas.drawImage(new_img, 90, 200, 400, 400, mask='auto') new_canvas.save() watermark = PdfFileReader(BytesIO(img_doc.getvalue())).getPage(0) pdf_in = PdfFileReader(input_path) pdf_out = PdfFileWriter() #Iterating on pages ading to each one for page_num in range(pdf_in.getNumPages()): page = pdf_in.getPage(page_num) page.mergePage(watermark) pdf_out.addPage(page) with open(output_path, 'wb') as output: pdf_out.write(output)
def pdf(): """Renders a PDF with barcodes generated from the querystring params 'b[].' """ barcodes = _get_barcodes(request.args, ignore_dimensions=False) # Start PDF generation buffer = BytesIO() pdf = canvas.Canvas(buffer) pdf.setTitle('barmycodes.pdf') # Generate barcodes and add to PDF for barcode in barcodes: # Add the barcode to the PDF barcode_buffer = BytesIO(barcode.as_string('png')) pdf.drawImage(ImageReader(barcode_buffer), 1, 1) barcode_buffer.close() pdf.setPageSize((barcode.width, barcode.height)) pdf.showPage() pdf.save() response = Response( buffer.getvalue(), mimetype='application/pdf', ) response.headers['Content-Disposition'] = 'inline; filename=barmycodes.pdf' buffer.close() return response
def _create_letter_header_footer(canvas, doc): # header current_y = PAGE_HEIGHT - LETTER_HEADER_MARGIN dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO) canvas.drawImage(dpaw_header_logo, LETTER_HEADER_MARGIN, current_y - LETTER_IMAGE_HEIGHT, width=LETTER_IMAGE_WIDTH, height=LETTER_IMAGE_HEIGHT) # footer current_x = PAGE_WIDTH - LETTER_HEADER_MARGIN current_y = LETTER_HEADER_MARGIN canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE) canvas.setFillColor(HexColor(LETTER_BLUE_FONT)) canvas.drawRightString(current_x, current_y, DPAW_URL) canvas.drawRightString( current_x, current_y + SMALL_FONTSIZE, 'Phone: {} Fax: {} Email: {}'.format(DPAW_PHONE, DPAW_FAX, DPAW_EMAIL)) canvas.drawRightString(current_x, current_y + SMALL_FONTSIZE * 2, DPAW_PO_BOX) canvas.setFont(BOLD_ITALIC_FONTNAME, SMALL_FONTSIZE) canvas.drawRightString(current_x, current_y + SMALL_FONTSIZE * 3, DPAW_BUSINESS)
def Reporte(request): product = Producto.objects.all() #Indicamos el tipo de contenido a devolver, en este caso un pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename= reporte-lab.pdf' #La clase io.BytesIO permite tratar un array de bytes como un fichero binario, se utilizacomo almacenamiento temporal buffer = BytesIO() #Canvas nos permite hacer el reporte con coordenadas X y Y pdf = canvas.Canvas(buffer, pagesize=A4) #Cabecera del reporte logo = ImageReader( 'https://cdn6.aptoide.com/imgs/4/5/a/45a6b5cdb2a4e4c51ba127f15427adf6_icon.png?w=60' ) pdf.drawImage(logo, 50, 770, mask='auto') pdf.drawString(30, 750, 'SEXSHOP CEREZAPP') pdf.drawString(30, 730, 'Reporte Productos') #Cuerpo del reporte n = 300 for ae in product: pdf.drawString(30, n, ae.nombre) pdf.drawString(200, n, ae.descripcion) pdf.drawString(500, n, str(ae.precio)) n += 20 pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def plot_overall_return(comb: pd.DataFrame, m_tick: str, plot: bool = False) -> ImageReader: """Generates overall return graph Parameters ---------- comb : pd.DataFrame Dataframe with returns m_tick : str The ticker for the market asset plot : bool Whether to plot the graph or return it for PDF Returns ---------- img : ImageReader Overal return graph """ fig, ax = plt.subplots(figsize=(10, 5)) ax.plot(comb.index, comb["return"], color="tab:blue", label="Portfolio") ax.plot(comb.index, comb[("Market", "Return")], color="orange", label=m_tick) ax.set_ylabel("", fontweight="bold", fontsize=12, color="black") ax.set_xlabel("") ax.yaxis.set_label_coords(-0.1, 0.5) ax.grid(True) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) fig.suptitle("Cumulative Performance", y=0.99, fontweight="bold", fontsize=14, color="black") ax.axhline(0, ls="-", lw=1, color="gray", zorder=1) ax.axhline(0, ls="--", lw=1, color="black", zorder=2) fig.set_facecolor("white") ax.set_title( f'{comb.index[:1][0].strftime("%Y/%m/%d")} - {comb.index[-1:][0].strftime("%Y/%m/%d")}', fontsize=12, color="gray", ) ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0)) ax.set_facecolor("white") ax.legend() fig.autofmt_xdate() if plot: plt.show() console.print("") return None imgdata = BytesIO() fig.savefig(imgdata, format="png") plt.close("all") imgdata.seek(0) return ImageReader(imgdata)
def printer_label(sample): """Generate the PDF of a sample for the label printer. :param sample: the sample the label of which should be generated :type sample: `samples.models.Sample` :return: the PDF as a byte stream :rtype: str """ output = StringIO() text = sample.name c = canvas.Canvas(output, pagesize=(width, height)) c.setAuthor("JuliaBase samples database") c.setTitle(text) c.setSubject("Label of {0} for the label printer".format(text)) try: print_line(c, 0, fontsize, text) except ExcessException: first, second = best_split(text) print_line(c, height / 2, fontsize_half, first, force=True) print_line(c, 0, fontsize_half, second, force=True) c.drawImage(ImageReader("http://chart.googleapis.com/chart?chs=116x116&cht=qr&chl={0}&chld=H|1".format(sample.id)), width - height, 0, height, height) c.showPage() c.save() return output.getvalue()
def logo(self): if not self._logo: path = get_static_file(self.logo_data["app_label"], self.logo_data["filename"]) if os.path.isfile(path): self._logo = ImageReader(path) return self._logo
def imgs_to_pdf(output, img_path_list): """将一组图片合成一个pdf文件 Args: output: 输出pdf文件路径 img_path_list: 要合成的图片的路径列表 Returns: output: 输出pdf文件路径 """ a4_w, a4_h = portrait(A4) c = canvas.Canvas(output, pagesize=portrait(A4)) for img_path in img_path_list: img_w, img_h = ImageReader(img_path).getSize() if img_w / img_h > a4_w / a4_h: # 宽的图片 ratio = a4_w / img_w left_margin = 0 top_margin = (a4_h - img_h * ratio) / 2 else: # 长的图片 ratio = a4_h / img_h left_margin = (a4_w - img_w * ratio) / 2 top_margin = 0 c.drawImage(img_path, left_margin, top_margin, img_w * ratio, img_h * ratio) c.showPage() c.save()
def payFees(request): if 'stu_roll' not in request.session: return HttpResponseRedirect('/user/login') else: form = PayFeesForm() if request.method == "POST": form = PayFeesForm(request.POST) fees = PayFees.objects.filter( stu_roll=request.session['stu_roll'], stu_semester=form.cleaned_data['stu_semester']) # if fees: if form.is_valid(): fees = PayFees() fees.stu_roll = request.session['stu_roll'] fees.stu_semester = form.cleaned_data['stu_semester'] fees.paid_amount = form.cleaned_data['paid_amount'] fees.receipt_no = form.cleaned_data['receipt_no'] fees.remarks = form.cleaned_data['remarks'] fees.save() student = Student.objects.get(stu_roll=fees.stu_roll) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="feesFile.pdf"' p = canvas.Canvas(response) logo = ImageReader('./static/images/nit.png') p.drawImage(logo, 40, 700, width=100, height=100, mask='auto') p.setFont("Helvetica", 20) p.drawString(150, 750, "XYZ Institute of Anything, College Place ") p.setFont("Helvetica", 14) p.drawString(50, 650, "Name : " + str(student.stu_name)) p.drawString(300, 650, "Roll No. : " + str(student.stu_roll)) p.drawString(50, 620, "Mobile No. : " + str(student.stu_mobile)) p.drawString(300, 620, "Email : " + str(student.stu_mail)) p.drawString( 50, 590, "Branch : " + str( Branch.objects.get( id=student.stu_branch_id).stu_branch)) p.drawString( 300, 590, "Course : " + str( Course.objects.get( id=student.stu_course_id).stu_course)) p.drawString(50, 560, "Semester : " + str(fees.stu_semester)) p.drawString(50, 520, "Fees ID : " + str(fees.id)) p.drawString(300, 520, "Receipt No : " + str(fees.receipt_no)) p.drawString(50, 490, "Remarks : " + str(fees.remarks)) p.showPage() p.save() return response else: stu = Student.objects.get(stu_roll=request.session['stu_roll']) sem = Semester.objects.all() fees = PayFees.objects.filter(stu_roll=request.session['stu_roll']) student = {"student": stu, "semesters": sem, "fees": fees} return render(request, 'pay.html', student)
def gera_pdf(self): row = self.tableWidget_clientes_3.currentRow() print(row) db = sqlite_db("agenda_bd.db") dados_lidos=db.pega_dados("SELECT *FROM clientes WHERE id={}".format(row)) y = 0 import time data_atual=time.strftime('%d-%m-%Y horas: %H:%M:%S', time.localtime()) logo = ImageReader('offsistema.png')#logo pdf = canvas.Canvas('{}.pdf'.format("OFF PACIENTES")) pdf.drawImage(logo, 400, 700,5*cm, 5*cm)#logo pdf.drawString(35,724,'='*20+ 'Dados cliente '+'='*20) pdf.drawString(35,750,'='*20+'OFF SISTEMA'+'='*20) pdf.drawString(10,5, f'Data: {data_atual}') pdf.drawString(30, 700, 'ID') pdf.drawString(30, 680, 'Nome: ')#nome pdf.drawString(250, 680, 'Data Nascimento : ')#NSACIMENTO pdf.drawString(430, 680, 'Idade: ')#idade pdf.drawString(30, 660, 'CPF: ')#cpf pdf.drawString(150, 660, 'Sexo: ')#SEXO pdf.drawString(240, 660, 'Email: ')# pdf.drawString(445, 660, 'Telefone: ')#telefone pdf.drawString(30, 640, 'Endereço: ')#ENDEREÇO pdf.drawString(270, 640, 'Nº: ')#NUMERO pdf.drawString(330, 640, 'Cidade: ')#CIDADE pdf.drawString(410, 640, 'Bairro: ')#BAIRRO pdf.drawString(515, 640, 'UF: ')#BAIRRO pdf.drawString(30, 620, 'Complemento: ')#COMPLEMENTO pdf.line(30,675,580,675)#linha cliente pdf.line(30,655,580,655)#enederço A telefone pdf.line(30,635,580,635)#linha cliente pdf.line(30,615,580,615)#complementos for i in range(0, len(dados_lidos)): y = y + 50 pdf.drawString(50, 750 - y, str(dados_lidos[i][0]))#id pdf.drawString(75, 730 - y, str(dados_lidos[i][1]))#NOME pdf.drawString(350, 730 - y, str(dados_lidos[i][10]))#DATA DE NASCIMENTO pdf.drawString(480, 730 - y, str(dados_lidos[i][2]))#IDADE pdf.drawString(60, 710 - y, str(dados_lidos[i][3]))#CPF pdf.drawString(180, 710 - y, str(dados_lidos[i][11]))#SEXO pdf.drawString(275, 710 - y, str(dados_lidos[i][4]))#EMAIL pdf.drawString(500, 710 - y, str(dados_lidos[i][12]))#TELEFONE pdf.drawString(95, 690 - y, str(dados_lidos[i][5]))#ENDEREÇO### pdf.drawString(290, 690 - y, str(dados_lidos[i][6]))#NUMERO##3 pdf.drawString(375, 690 - y, str(dados_lidos[i][7]))#CIDADE pdf.drawString(450, 690 - y, str(dados_lidos[i][8]))#BAIRRO pdf.drawString(540, 690 - y, str(dados_lidos[i][13]))#estado pdf.drawString(110, 670 - y, str(dados_lidos[i][9]))#COMPLEMENTO # background: url("D:/pytho willow/agenda/icon/LOGO FUNDO.png") no-repeat; pdf.save() QMessageBox.about(self, "PDF", "O PDF FOI GERADO COM SUCESSO") print('O PDF FOI GERADO COM SUCESSO')
def _draw_item(self, canvas, item, tpl_data, content, margin_x, margin_y): font_size = _extract_font_size(item['font_size']) styles = { 'alignment': ALIGNMENTS[item['text_align']], 'textColor': item.get('color') or '#000000', 'backColor': item.get('background_color') or None, 'borderPadding': (0, 0, 4, 0), 'fontSize': font_size, 'leading': font_size } if item['bold'] and item['italic']: styles['fontName'] = FONT_STYLES[item['font_family']][3] elif item['italic']: styles['fontName'] = FONT_STYLES[item['font_family']][2] elif item['bold']: styles['fontName'] = FONT_STYLES[item['font_family']][1] else: styles['fontName'] = FONT_STYLES[item['font_family']][0] for update in values_from_signal( signals.event.designer.update_badge_style.send(self.template, item=item, styles=styles), as_list=True): styles.update(update) style = ParagraphStyle({}) for key, value in styles.items(): setattr(style, key, value) item_x = float(item['x']) / PIXELS_CM * cm item_y = float(item['y']) / PIXELS_CM * cm item_width = item['width'] / PIXELS_CM * cm item_height = (item['height'] / PIXELS_CM * cm) if item.get('height') is not None else None if isinstance(content, Image.Image): canvas.drawImage(ImageReader(content), margin_x + item_x, self.height - margin_y - item_height - item_y, item_width, item_height, mask='auto') else: content = strip_tags(content) for line in content.splitlines(): p = Paragraph(line, style) available_height = (tpl_data.height_cm - (item_y / PIXELS_CM)) * cm w, h = p.wrap(item_width, available_height) if w > item_width or h > available_height: # TODO: add warning pass p.drawOn(canvas, margin_x + item_x, self.height - margin_y - item_y - h) item_y += h
def drawLogo(self, name="V&A-logo.png"): # print("Logo is %s" % getImageData(name)[0]) self.canvas.saveState() logo = ImageReader(name) # parts.append(Image(name)) # print("Logo is %s" % logo) self.canvas.drawImage(name, PAGE_HEIGHT*0.9, PAGE_WIDTH*0.85, mask='auto', width=PAGE_WIDTH*0.1, height=PAGE_WIDTH*0.1, preserveAspectRatio=True) self.canvas.restoreState()
def createPDF(id, forename, surname, category): #Creating file canvas = Canvas(f"reconocimiento-{id}.pdf", pagesize=letter) width, height = letter #Background image and rectangle for information bg_im = ImageReader("assets/bg_image.jpg") logo = ImageReader("assets/logo.png") canvas.drawImage(image=bg_im, x=0, y=0, width=width, height=height) canvas.drawImage(image=logo, x=inch / 2, y=height - 1.5 * inch, width=inch, height=inch) gray50transparent = Color(160, 160, 160, alpha=0.75) canvas.setFillColor(gray50transparent) canvas.rect(0.5 * inch, 2 * inch, width - inch, height - 4 * inch, fill=True, stroke=False) #Text canvas.setFont('Helvetica', 20) canvas.setFillColor(Color(0, 0, 0, alpha=1)) #Black canvas.drawCentredString(width / 2, 8 * inch, "Torneo de Programación Competitiva") canvas.drawCentredString(width / 2, 7.5 * inch, "Copa Guadalajara 2021") canvas.drawCentredString(width / 2, 6 * inch, "Se otorga el reconocimiento a:") canvas.setFont('Helvetica-Bold', 20) canvas.drawCentredString(width / 2, 5.5 * inch, f'{forename} {surname}') canvas.setFont('Helvetica', 20) canvas.drawCentredString( width / 2, 4 * inch, f"Por su participación en la categoría {category}") canvas.drawCentredString(width / 2, 3.5 * inch, 'en la copa de programación competitiva') canvas.drawCentredString(width / 2, 3 * inch, 'Guadalajara 2021.') #Closing file canvas.save()
def process_return_label(pdf_file): image = list(get_images(pdf_file))[0] image_reader = ImageReader(image) with open(pdf_file, 'wb') as fp: writer = PdfFileWriter() writer.addPage(get_image_page(image_reader)) writer.write(fp)
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 pdf(self): stream = BytesIO() pdf = Canvas(stream) pdf.drawImage(ImageReader(self.img), *self.dimensions) pdf.save() return PdfFileReader(stream).getPage(0)
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 __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 _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, '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 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 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