def generate_check(to, price, filename): fontsize = 16 font = ImageFont.truetype("arial.ttf", fontsize) today = date.today() d = today.strftime("%d") m = today.strftime("%m") y = today.strftime("%Y") price_word = nw(price).replace(",", "") + " only" acc_no = "1234567890" path = (Path.home() / "cheque.png") sign_path = (Path.home() / "signature.png") img = Image.open(path) d1 = ImageDraw.Draw(img) d1.text((488, 18), d[0], fill=(0, 0, 0)) d1.text((503, 18), d[1], fill=(0, 0, 0)) d1.text((518, 18), m[0], fill=(0, 0, 0)) d1.text((533, 18), m[1], fill=(0, 0, 0)) d1.text((548, 18), y[0], fill=(0, 0, 0)) d1.text((563, 18), y[1], fill=(0, 0, 0)) d1.text((578, 18), y[2], fill=(0, 0, 0)) d1.text((593, 18), y[3], fill=(0, 0, 0)) d1.text((100, 52), to, font=font, fill=(0, 0, 0)) d1.text((100, 79), price_word, font=font, fill=(0, 0, 0)) d1.text((80, 136), acc_no, font=font, fill=(0, 0, 0)) d1.text((500, 102), str(price), font=font, fill=(0, 0, 0)) signature = Image.open(sign_path) img.paste(signature, (450, 170)) #img.show() img.save(filename)
def index(): import StringIO # fairy = FairyImage.getrandomfairy() # imgstring = fairy['image'] # filelike = StringIO.StringIO(imgstring) # canvas = Image.open(filelike) # canvas = FairyImage.addFairyNametoImage(canvas, fairy) # output=StringIO.StringIO() # canvas.save(output, format="JPEG") # contents= output.getvalue().encode('base64') # output.close() # # return render_template("index.html",contents=urllib.quote(contents.rstrip('\n'))) x = random.randint(1, 3) if (x == 1): princesses = Image.open("static/Princess_Tabitha.png") name = ("Tabitha") elif (x == 2): princesses = Image.open("static/Princess_Esme.png") name = ("Esme") else: princesses = Image.open("static/Princess_Violet.png") name = ("Violet") canvas = princesses output = StringIO.StringIO() canvas.save(output, format="JPEG") contents = output.getvalue().encode('base64') return render_template("index.html", contents=urllib.quote(contents.rstrip('\n')), Princess_name=name)
def gerarPDF(): c = canvas.Canvas(nomearquivoPDF, pagesize=letter) try: for i in imagens: #print(i) #c.drawImage(i, inch, inch * 1) a = Image.open(i) a.drawHeight = 2*inch a.drawWidth = 2*inch data=[['1',a],['3','4']] c = canvas.Canvas("Reportlabtest.pdf", pagesize=portrait(A4)) table = Table(data, colWidths=200, rowHeights=50) table.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('BACKGROUND',(0,0),(-1,2),colors.lightgrey) ])) table.wrapOn(c, 200, 400) table.drawOn(c,20,50) c.save() if limpaTemp(): #c.save() print ("PDF criado") except: print ("PDF não criado") limpaTemp() return
def topdf(image_file: str, left=0, top=0): # image_file: str = "./test.png" # image_file = "https://zyai.jxwifi.com/uploads/20201203/ae26751e48348f0765322f9eb26a5a32.png" uuidName = str(uuid.uuid4()) pdfName = uuidName + '.pdf' c = canvas.Canvas(getUploadDir() + '/' + pdfName, pagesize=A3) width, height = A3 if image_file[-3:].lower() == 'png': jpgName = download_img(image_file, uuidName) im = Image.open(getUploadDir() + "/" + jpgName) x, y = im.size p = Image.new('RGBA', im.size, (255, 255, 255)) p.paste(im, (0, 0, x, y), im) savePath = getUploadDir() + "/" + uuidName + '.png' p.save(savePath) c.drawImage(savePath, left, top, width, height) else: #c.drawImage(image_file, 0, 0, width, height) #c.drawInlineImage(image_file, 0, 0) # c.showPage() c.drawImage(image_file, left, top, width, height) c.save() return pdfName
def redimensiona(): with open("error.txt", "w") as a: for path, subdirs, files in os.walk(r'.'): for filename in files: if not(marcaTemp in filename): if(".jpg" in filename) or (".JPG" in filename) or (".jpeg" in filename) or (".JPEG" in filename): f = os.path.join(path, filename) print("trabalhando imagem "+f) imagem = Image.open(f) largura_imagem = imagem.size[0] try: altura_imagem = imagem.size[1] percentual_largura = float(largura_desejada) / float(largura_imagem) altura_desejada = int((altura_imagem * percentual_largura)) imagem = imagem.resize((largura_desejada, altura_desejada), Image.ANTIALIAS) g = f+marcaTemp imagem.save(g) imagens.append(g) except Exception as ERROR: a.write(str(f) + os.linesep) a.write(str(ERROR) + os.linesep) continue else: continue else: f = os.path.join(path, filename) print("trabalhando imagem "+f) imagens.append(g) return
def write_predictons(model, img, y, c, model_pth): x = 300 op_img = Image.open(img).convert('L') np_img = np.array(op_img) predictions = make_prediction(model, np_img) init_pred = predictions[0, 0] index = 0 for pred in range(1, len(predictions[0])): if init_pred < predictions[0, pred]: init_pred = predictions[0, pred] index = pred num_y = y + 110 for i in range(len(predictions[0])): c.drawString(x, num_y, '%0.5f' % predictions[0, i]) if i == index and i == 0: rec_color = Color(0, 100, 0, alpha=0.5) c.setFillColor(rec_color) c.rect(x - 2, num_y - 5, 49, 20, stroke=1, fill=1) c.setFillColor(black) elif i == index: rec_color = Color(100, 0, 0, alpha=0.5) c.setFillColor(rec_color) c.rect(x - 2, num_y - 5, 49, 20, stroke=1, fill=1) c.setFillColor(black) num_y -= 20 text_x = x + 50 if (str(model).split('_'))[2] == str(1): c.drawString(text_x, y + 110, 'Negative') c.drawString(text_x, y + 90, 'Benign calcification') c.drawString(text_x, y + 70, 'Benign mass') c.drawString(text_x, y + 50, 'Malignant calcification') c.drawString(text_x, y + 30, 'Malignant mass') elif str(model).split('_')[2] == str(2): if str(model_pth).split('_')[6] == 'neg': c.drawString(text_x, y + 110, 'Negative') c.drawString(text_x, y + 90, 'Positive') elif str(model_pth).split('_')[6] == 'bc': c.drawString(text_x, y + 110, 'Other diagnosis') c.drawString(text_x, y + 90, 'Benign calcification') elif str(model_pth).split('_')[6] == 'bm': c.drawString(text_x, y + 110, 'Other diagnosis') c.drawString(text_x, y + 90, 'Benign mass') elif str(model_pth).split('_')[6] == 'mc': c.drawString(text_x, y + 110, 'Other diagnosis') c.drawString(text_x, y + 90, 'Malignant calcification') elif str(model_pth).split('_')[6] == 'mm': c.drawString(text_x, y + 110, 'Other diagnosis') c.drawString(text_x, y + 90, 'Malignant mass') if index > 0: return index else: return 0
def login(): import StringIO fairy = FairyImage.getrandomfairy() imgstring = fairy['image'] filelike = StringIO.StringIO(imgstring) canvas = Image.open(filelike) canvas = FairyImage.addFairyNametoImage(canvas, fairy) output = StringIO.StringIO() canvas.save(output, format="JPEG") contents = output.getvalue().encode('base64') output.close() return render_template("index.html", contents=urllib.quote(contents.rstrip('\n')))
def dibujar_logo(canvas, doc, ruta_logo): """ Dibuja el logotipo de la empresa en la página de «canvas». """ if ruta_logo: im = Image.open(ruta_logo) ancho, alto = im.size nuevo_alto = min(3 * cm, alto) ancho_proporcional = ancho * (nuevo_alto / alto) canvas.drawImage(ruta_logo, PAGE_WIDTH - 3 * cm - ancho_proporcional, PAGE_HEIGHT - 2 * cm - nuevo_alto, ancho_proporcional, nuevo_alto)
def home(): import StringIO fairy = FairyImage.getrandomfairy() imgstring = fairy['image'] filelike = StringIO.StringIO(imgstring) canvas = Image.open(filelike) canvas = FairyImage.addFairyNametoImage(canvas, fairy) output = StringIO.StringIO() canvas.save(output, format="JPEG") contents = output.getvalue().encode('base64') output.close() isadmin = current_user.has_role('superuser') loggedin = current_user.is_authenticated return render_template("main.html", contents=urllib.quote(contents.rstrip('\n')), admin=isadmin, auth=loggedin)
def genLongImage(args): ''' 生成长图 ''' try: drawGentt(args[:3]) drawTable(args) imgs = [ Image.open(f'static/{fn}') for fn in listdir(path='static/') if fn.endswith('.png') ] width, height = imgs[0].size result = Image.new(imgs[0].mode, (width, height * len(imgs))) for index, img in enumerate(imgs): result.paste(img, box=(0, index * height)) result.save('pws.png') except Exception: return False return True
def prettyPicture(): im = Image.open("C:\Python27\dozer.jpg") b.drawImage("C:\Python27\dozer.jpg",3*(width/45),height-height/2.2,width=width-6*(width/45),height=height/2.7)
# ('BOX', (0, 0), (-1, 0), 0.25, colors.green), # ('ALIGN', (0, 0), (-1, 0), 'CENTER'), # ])) # parts.append(table) # parts.append(Spacer(1, 0.5 * inch)) # parts.append(table_with_style) # doc.build(parts) from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, cm, landscape from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, Table, TableStyle, Image from reportlab.lib.enums import TA_LEFT, TA_CENTER from reportlab.lib import colors from reportlab.lib.units import inch a = Image.open("svg.svg") a.drawHeight = 2 * inch a.drawWidth = 2 * inch data = [['1', a], ['3', '4']] c = canvas.Canvas("Reportlabtest.pdf", pagesize=landscape(A4)) table = Table(data, colWidths=200, rowHeights=50) table.setStyle( TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 2), colors.lightgrey)])) table.wrapOn(c, 200, 400) table.drawOn(c, 20, 50) c.save()
figcnt = 0 qrcodeimagepath = utbiomelocation+"PNGFIGURES" tmpsavefolder = utbiomelocation+"tempSaveFolder" if os.path.exists(tmpsavefolder): shutil.rmtree(tmpsavefolder) os.mkdir(tmpsavefolder) else: os.mkdir(tmpsavefolder) for f in os.listdir(qrcodeimagepath): print f figcnt = figcnt+1 new_im = Image.new('RGB', (1050,400)) qr_file = qrcodeimagepath +'\\'+ f im = Image.open(qr_file) #Here I resize my opened image, so it is no bigger than 100,100 #im.thumbnail((210,198)) #Iterate through a 4 by 4 grid with spacing, to place my image for i in xrange(0,1050,210): for j in xrange(0,400,198): #paste the image at location i,j: new_im.paste(im, (i,j)) new_im.show() new_im.save(tmpsavefolder+"\\new_imout"+str(figcnt)+".png","png") # Now lets collect the stitched QRCode Images and append to the story doc and make the pdf stitchedQrcodesPath = tmpsavefolder for qr in os.listdir(stitchedQrcodesPath): print qr qrImage = stitchedQrcodesPath+'\\'+qr
def fill_page_with_image(path, canvas): """ Given the path to an image and a reportlab canvas, fill the current page with the image. This function takes into consideration EXIF orientation information (making it compatible with photos taken from iOS devices). This function makes use of ``canvas.setPageRotation()`` and ``canvas.setPageSize()`` which will affect subsequent pages, so be sure to reset them to appropriate values after calling this function. :param path: filesystem path to an image :param canvas: ``reportlab.canvas.Canvas`` object """ from PIL import Image page_width, page_height = canvas._pagesize image = Image.open(path) image_width, image_height = image.size if hasattr(image, '_getexif'): orientation = (image._getexif() or {}).get(274, 1) # 274 = Orientation else: orientation = 1 # These are the possible values for the Orientation EXIF attribute: ORIENTATIONS = { 1: "Horizontal (normal)", 2: "Mirrored horizontal", 3: "Rotated 180", 4: "Mirrored vertical", 5: "Mirrored horizontal then rotated 90 CCW", 6: "Rotated 90 CW", 7: "Mirrored horizontal then rotated 90 CW", 8: "Rotated 90 CCW", } draw_width, draw_height = page_width, page_height if orientation == 1: canvas.setPageRotation(0) elif orientation == 3: canvas.setPageRotation(180) elif orientation == 6: image_width, image_height = image_height, image_width draw_width, draw_height = page_height, page_width canvas.setPageRotation(90) elif orientation == 8: image_width, image_height = image_height, image_width draw_width, draw_height = page_height, page_width canvas.setPageRotation(270) else: raise ValueError("Unsupported image orientation '%s'." % ORIENTATIONS[orientation]) if image_width > image_height: page_width, page_height = page_height, page_width # flip width/height draw_width, draw_height = draw_height, draw_width canvas.setPageSize((page_width, page_height)) # Ameriks custom implementation to position in the middle image. # TODO: Testing with rotated image draw_width = page_width draw_height = (page_width * image_height) / image_width if draw_height < page_height: draw_height = page_height draw_width = (page_height * image_width) / image_height x = 0 if draw_width > page_width: x = (page_width - draw_width) / 2.0 y = 0 if draw_height > page_height: y = (page_height - draw_height) / 2.0 canvas.drawImage(path, x, y, width=draw_width, height=draw_height, preserveAspectRatio=True)
def Create_Pdf(request): filename = request.data['file'] + ".pdf" pdf = SimpleDocTemplate(filename, pagesize=letter) BASE_DIR = getattr(settings, "BASE_DIR", None) customColor = colors.Color(red=(74.0 / 255), green=(98.0 / 255), blue=(255.0 / 255)) customColor1 = colors.Color(red=(150.0 / 255), green=(180.0 / 255), blue=(255.0 / 255)) customColor2 = colors.Color(red=(255.0 / 255), green=(255.0 / 255), blue=(255.0 / 255)) def setBackground(table, rowNumb): for i in range(1, rowNumb): if i % 2 == 0: bc = customColor1 else: bc = customColor2 ts = TableStyle([('BACKGROUND', (0, i), (-1, i), bc), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 0), customColor), ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, 0), 14), ('BOTTOMPADDING', (0, 0), (-1, 0), 12)]) table.setStyle(ts) def setIncomeBackground(table, rowNumb): for i in range(1, rowNumb): if i % 2 == 0: bc = customColor1 else: bc = customColor2 ts = TableStyle([ ('BACKGROUND', (0, i), (-1, i), bc), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ]) table.setStyle(ts) elems = [] if request.data['file'] == 'sales_report': #print("SELECT sales.item_code, food.name, sales.quantity, food.price*sales.quantity as COST , CAST(sales.date AS char) FROM food inner JOIN sales ON FOOD.ITEM_CODE = SALES.ITEM_CODE where date(sales.date) >= {}".format(request.data['date'])) print(request.data['date']) print( "SELECT sales.item_code, food.name, sales.quantity, food.price*sales.quantity as COST , CAST(sales.date AS char) FROM food inner JOIN sales ON FOOD.ITEM_CODE = SALES.ITEM_CODE where date(sales.date) >= {}" .format(request.data['date'])) sales_data = list( my_custom_sql( "SELECT sales.item_code, food.name, sales.quantity, food.price*sales.quantity as COST , CAST(sales.date AS char) FROM food inner JOIN sales ON FOOD.ITEM_CODE = SALES.ITEM_CODE where date(sales.date) >= {}" .format(request.data['date']))) sales_head = ["Item Code", "Food name", "Quatity", "Cost", "Sale time"] sales_data.insert(0, sales_head) sales_table = Table(sales_data) setBackground(sales_table, len(sales_data)) elems.append( Paragraph( "Sales report from " + datetime.strptime( request.data['date'], "%Y-%m-%d").strftime("%d-%m-%Y"), ParagraphStyle("List", parent=getSampleStyleSheet()['Heading1'], alignment=1, spaceAfter=30))) elems.append(sales_table) elif request.data['file'] == 'purchase_report': purchase_data = list( my_custom_sql( "select purchase.ingredient_id, inventory.name, purchase.quantity, purchase.price, cast(purchase.date as char) from purchase inner join inventory on purchase.ingredient_id = inventory.ingredient_id where purchase.date >= {}" .format(request.data['date']))) purchase_head = [ "Ingredient Id", "Ingredient name", "Quantity", "Price", "Purchase time" ] purchase_data.insert(0, purchase_head) purchase_table = Table(purchase_data) setBackground(purchase_table, len(purchase_data)) elems.append( Paragraph( "Purchase report from " + datetime.strptime( request.data['date'], "%Y-%m-%d").strftime("%d-%m-%Y"), ParagraphStyle("List", parent=getSampleStyleSheet()['Heading1'], alignment=1, spaceAfter=30))) elems.append(purchase_table) else: sales_data = list( my_custom_sql( "SELECT sales.item_code, food.name, sales.quantity, food.price*sales.quantity as COST , CAST(sales.date AS char) FROM food inner JOIN sales ON FOOD.ITEM_CODE = SALES.ITEM_CODE where date(sales.date) >= {}" .format(request.data['date']))) purchase_data = list( my_custom_sql( "select purchase.ingredient_id, inventory.name, purchase.quantity, purchase.price, cast(purchase.date as char) from purchase inner join inventory on purchase.ingredient_id = inventory.ingredient_id where purchase.date >= {}" .format(request.data['date']))) monthly_sales = list( my_custom_sql(''' select sum(if(month = 'Jan', total, 0)) as 'Jan', sum(if(month = 'Feb', total, 0)) as 'Feb', sum(if(month = 'Mar', total, 0)) as 'Mar', sum(if(month = 'Apr', total, 0)) as 'Apr', sum(if(month = 'May', total, 0)) as 'May', sum(if(month = 'Jun', total, 0)) as 'Jun', sum(if(month = 'Jul', total, 0)) as 'Jul', sum(if(month = 'Aug', total, 0)) as 'Aug', sum(if(month = 'Sep', total, 0)) as 'Sep', sum(if(month = 'Oct', total, 0)) as 'Oct', sum(if(month = 'Nov', total, 0)) as 'Nov', sum(if(month = 'Dec', total, 0)) as 'Dec' from( select date_format(sales.date, "%b") as month, sum(food.price*sales.quantity) as total from food inner join sales on sales.item_code = food.item_code where date(sales.date) <= now() and date(sales.date) >= date_add(now(), interval -12 month) group by date_format(date(sales.date), "%m-%Y")) as sub ''')) monthly_purchase = list( my_custom_sql(''' select sum(if(month = 'Jan', total, 0)) as 'Jan', sum(if(month = 'Feb', total, 0)) as 'Feb', sum(if(month = 'Mar', total, 0)) as 'Mar', sum(if(month = 'Apr', total, 0)) as 'Apr', sum(if(month = 'May', total, 0)) as 'May', sum(if(month = 'Jun', total, 0)) as 'Jun', sum(if(month = 'Jul', total, 0)) as 'Jul', sum(if(month = 'Aug', total, 0)) as 'Aug', sum(if(month = 'Sep', total, 0)) as 'Sep', sum(if(month = 'Oct', total, 0)) as 'Oct', sum(if(month = 'Nov', total, 0)) as 'Nov', sum(if(month = 'Dec', total, 0)) as 'Dec' from( select date_format(purchase.date, "%b") as month, sum(purchase.price) as total from purchase inner join inventory on purchase.ingredient_id = inventory.ingredient_id where date(purchase.date) <= now() and date(purchase.date) >= date_add(now(), interval -12 month) group by date_format(date(purchase.date), "%m-%Y")) as sub ''')) print(monthly_purchase) monthly_income = [] for i in range(12): monthly_income.append( float(monthly_sales[0][i]) - float(monthly_purchase[0][i])) mon = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] curmonth = datetime.now().month curyear = datetime.now().year months = ["{} {}".format(i, str(curyear - 1)) for i in mon[curmonth:]] cur_yr = ["{} {}".format(i, str(curyear)) for i in mon[:curmonth]] months.extend(cur_yr) print(months) print(monthly_income) gross_income_data = [] total_sales = sum([i[3] for i in sales_data]) total_purchase = sum([i[3] for i in purchase_data]) gross_income = total_sales - total_purchase gross_income_data.append(("Total sales amount", total_sales)) gross_income_data.append(("Total purchase amount", total_purchase)) gross_income_data.append(( "Loss", abs(gross_income)) if gross_income < 0 else ("Profit", gross_income)) gross_income_table = Table(gross_income_data, colWidths=(4 * inch, 1 * inch)) plt.figure(figsize=(4, 4)) plt.xlabel("Month") plt.ylabel("Income") plt.title("Monthly income comparison") plt.xticks(rotation=90) plt.yticks(rotation=90) plt.axhline(y=0, c='g', linewidth=1, ls='--') plt.plot(months, monthly_income, marker='o') plt.savefig("monthly_comparison.png", bbox_inches="tight") image_link = os.path.join(BASE_DIR, "monthly_comparison.png") setIncomeBackground(gross_income_table, len(gross_income_data)) elems.append( Paragraph( "Gross Income from " + datetime.strptime( request.data['date'], "%Y-%m-%d").strftime("%d-%m-%Y"), ParagraphStyle("List", parent=getSampleStyleSheet()['Heading1'], alignment=1, spaceAfter=30))) elems.append(gross_income_table) elems.append(Paragraph("", ParagraphStyle("List", spaceAfter=15))) elems.append(Image.open(image_link)) pdf.build(elems) #print("ok") #return Response("ok") try: path_to_file = os.path.join(BASE_DIR, filename) f = open(path_to_file, 'rb') pdfFile = File(f) response = HttpResponse(pdfFile, content_type='applicaiton/pdf') response['Content-Disposition'] = 'inline;filename="{}.pdf"'.format( filename) return response except FileNotFoundError: raise Http404()
def topdf(path, recursion=None, pictureType=None, sizeMode=None, width=None, height=None, fit=None, save=None): if platform.system() == 'Windows': path = path.replace('\\', '/') if path[-1] != '/': path = (path + '/') # print(path) if recursion == True: for i in os.listdir(path): if os.path.isdir(os.path.abspath(os.path.join(path, i))): topdf(path + i, recursion, pictureType, sizeMode, width, height, fit, save) filelist = [] if pictureType == None: filelist = glob.glob(os.path.join(path, '*.jpg')) else: picName = var2.get() for i in pictureType: hellopic = glob.glob(os.path.join(path, '*.' + i)) hellopic.sort(key=lambda x: len(x)) if picName == '': filelist.extend(hellopic) else: for j in hellopic: file_path = os.path.split(j) #分割出目录与文件 file_path1 = file_path[0].split('.') lists = file_path[1].split('.') #分割出文件与文件扩展名 file_ext = lists[0] #取出后缀名(列表切片操作) if picName in file_ext: filelist.append(j) maxw = 0 maxh = 0 if sizeMode == None or sizeMode == 0: for i in filelist: im = Image.open(i) if maxw < im.size[0]: maxw = im.size[0] if maxh < im.size[1]: maxh = im.size[1] elif sizeMode == 1: maxw = 999999 maxh = 999999 for i in filelist: im = Image.open(i) print(i) if maxw > im.size[0]: maxw = im.size[0] if maxh > im.size[1]: maxh = im.size[1] else: if width == None or height == None: raise Exception("没有提供宽度或者高度") maxw = width maxh = height maxsize = (maxw, maxh) save1 = var3.get() fileLength = filelist.__len__() if (fileLength > 0): filename_pdf = path + save1 + '.pdf' c = canvas.Canvas(filename_pdf, pagesize=maxsize) l = len(filelist) for i in range(l): (w, h) = maxsize width, height = letter if fit == True: c.drawImage(filelist[i], 0, 0) else: c.drawImage(filelist[i], 0, 0, maxw, maxh) c.showPage() c.save() tk.Label(window, text='成功转换!').place(x=20, y=260)
from reportlab.pdfgen import canvas from reportlab.platypus import Image from reportlab.lib.units import inch, mm from PIL import Image, ImageChops, ImageDraw, ImagePath, ImageFont import numpy c = canvas.Canvas("hello.pdf", pagesize=(1562, 221 * mm)) # logo = "images/1.png" # logo_width,logo_height = 1043,445 # image = Image(logo,logo_width,logo_height) # image = Image.open("images/1.png").save('lalala.png') # c.drawImage(image,0,0) # hello(c) c.drawString(226, 110, "Hello") hair = Image.open("images/ab_thumb_male_hair_straight.png") white_back = Image.open("lalala.png") txt = Image.new('RGBA', white_back.size, (255, 255, 255, 0)) d = ImageDraw.Draw(txt) font = ImageFont.truetype("arial.ttf", size=20) d.text((20, 20), "Hello WORLD!", fill=(0, 0, 0, 255), font=font) # d.text((20,100),"Hello WORLD2!",fill=(0,0,0,255)) white_back.paste(hair, (700, 20), hair) # TEXT TRANSFORMATION def find_coeffs(pa, pb): matrix = [] for p1, p2 in zip(pa, pb): matrix.append( [p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]])
__author__ = 'SarcasMe' import os # import urllib2 import time from reportlab import platypus from reportlab.lib.pagesizes import letter from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Image from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, portrait, landscape from PIL import Image image_file = "42.jpg" im = Image.open(image_file) im_width = im.size[0] im_height = im.size[1] size = int(im_width * 5), int(im_height * 5) # 分割文件路径和后缀名 FilePath, Fileext = os.path.splitext(image_file) # 设置保存后的文件格式 outImageFile = "{0}.jpg".format(FilePath) # 打开并保存 im.thumbnail(size) im.save(outImageFile) # (w, h) = portrait(A4) # # Use Canvas to generate pdf # c = canvas.Canvas('reportlab_canvas.pdf', pagesize = portrait(A4)) # # #c.setFillColorRGB(0,0.77,0.77)
def generate_usps_tracking_no(self, picking, error=False): ''' This function is used to Generated USPS Shipping Label in Delivery order parameters: picking : (int) stock picking ID,(delivery order ID) ''' sale_id = self.env['sale.order'].search([('name', '=', picking.origin) ]) context = dict(self._context or {}) if not self.env['shipping.usps'].search([('active', '=', True)]): raise osv.except_osv(_('Error'), _('Default Endicia settings not defined')) ship_endicia = self.env['shipping.usps'].search([('active', '=', True) ]) context['usps_active'] = False #Endicia Quotes Selected stockpicking_obj = self.env['stock.picking'] if picking.service_type_usps.find('First') != -1: mail_class = 'First' elif picking.service_type_usps.find('Express') != -1: mail_class = 'Express' else: mail_class = picking.service_type_usps cust_address = ship_endicia.config_shipping_address_id shipper = Address( cust_address.name or '', cust_address.street, cust_address.street2 or '', cust_address.city, cust_address.state_id.code or '', cust_address.zip, cust_address.country_id.code, cust_address.phone or '', cust_address.email, (cust_address.name != cust_address.name) and cust_address.name or '') cust_address = picking.partner_id receipient = Address( cust_address.name or '', cust_address.street and cust_address.street.rstrip(','), cust_address.street2 and (cust_address.street != cust_address.street2) and cust_address.street2.rstrip(',') or '', cust_address.city and cust_address.city.rstrip(','), cust_address.state_id.code or '', cust_address.zip, cust_address.country_id.code, cust_address.phone or '', cust_address.email, (cust_address.name != cust_address.name) and cust_address.name or '') international_label = False if receipient.country_code.lower( ) != 'us' and receipient.country_code.lower( ) != 'usa' and receipient.country_code.lower() != 'pr': international_label = True if picking.service_type_usps.find('First') != -1: mail_class = 'FirstClassMailInternational' elif picking.service_type_usps.find('Express') != -1: mail_class = 'ExpressMailInternational' elif picking.service_type_usps.find('Priority') != -1: mail_class = 'PriorityMailInternational' package = endicia.Package( mail_class, int( round(picking.weight_package * 10 >= 1.0 and picking.weight_package * 10 or 1.0)), endicia.Package.shapes[picking.container_usps], picking.length_package, picking.width_package, picking.height_package, picking.name, sale_id.amount_total) customs = [] if international_label: for move_line in picking.move_lines: weight_net = move_line.product_id.product_tmpl_id.weight_net * 16 >= 1.0 and move_line.product_id.product_tmpl_id.weight_net * 16 * move_line.product_qty or 1.0 customs.append( endicia.Customs( move_line.product_id.default_code + '-' + move_line.product_id.name, int(move_line.product_qty), int(round(weight_net)), move_line.price_unit > 0.00 and move_line.price_unit or 39.00, shipper.country_code)) reference = '' reference2 = '' for move_line in picking.move_lines: reference += ' (' + str(int(move_line.product_qty)) + ')' if move_line.product_id.default_code: reference += str(move_line.product_id.default_code) + '+' reference = reference[:-1] reference = reference[20:] reference2 += ' ' + ship_endicia.config_shipping_address_id.name # try: include_postage = picking.include_postage_usps if picking.service_type_usps.find( 'International' ) != -1 or picking.container_usps == 'Letter' != -1: image_rotation = 'Rotate90' else: image_rotation = ship_endicia.image_rotation request = endicia.LabelRequest( ship_endicia.requester_id, ship_endicia.account_id, ship_endicia.passphrase, ship_endicia.label_type if not international_label else 'International', ship_endicia.label_size, ship_endicia.image_format, image_rotation, package, shipper, receipient, reference, reference2, include_postage, debug=ship_endicia.test, destination_confirm=True if picking.service_type_usps == 'First Class' and picking.container_usps == 'Letter' else False, customs_info=customs) response = request.send() if isinstance(response, (str)): log_data = picking.write({ 'error_for_faulty': str(response), 'is_faulty_deliv_order': True }) return True endicia_res = response._get_value() im_barcode = cStringIO.StringIO( endicia_res['label']) # constructs a StringIO holding the image img_barcode = Image.open(im_barcode) output = StringIO.StringIO() img_barcode.save(output, format='PNG') data = binascii.b2a_base64(output.getvalue()) f = open('/tmp/test.png', 'wb') f.write(output.getvalue()) f.close() c = canvas.Canvas("/tmp/picking_list.pdf") c.setPageSize((400, 650)) c.drawImage('/tmp/test.png', 10, 10, 380, 630) c.save() f = open('/tmp/picking_list.pdf', 'rb') attachment_pool = self.env['ir.attachment'] data_attach = { 'name': 'PackingList.pdf', 'datas': base64.b64encode(f.read()), 'description': 'Packing List', 'res_name': picking.name, 'res_model': 'stock.picking', 'res_id': picking.id, } attach_id = attachment_pool.search([('res_id', '=', picking.id), ('res_name', '=', picking.name)]) if not attach_id: attach_id = attachment_pool.create(data_attach) os.remove('/tmp/test.png') os.remove('/tmp/picking_list.pdf') else: attach_result = attachment_pool.write(cr, uid, attach_id, data_attach) attach_id = attach_id[0] context['attach_id'] = attach_id if endicia_res['tracking']: carrier_id = self.env['delivery.carrier'].search([ ('service_code', '=', picking.service_type_usps), ('container_usps', '=', picking.container_usps) ]) if len(carrier_id): carrier_id = carrier_id[0] cost = endicia_res['cost'] else: carrier_id = False cost = False vals = { 'carrier_tracking_ref': endicia_res['tracking'], 'carrier_id': carrier_id.id, 'shipping_rate': cost } picking.write(vals) context['track_success'] = True context['tracking_no'] = endicia_res['tracking'] return True
def randompdfcard(): PAGE_size = 180, 252 IMG_size = 270, 378 l = FairyImage.getfairyreferences("FAIRY_TBL") numgirl = (len(l[0])) numboy = (len(l[1])) # Get a list of all Fairy IDs Ids = [] for x in range(0, numgirl - 1): Ids.append(l[0][x][0]) for y in range(0, numboy - 1): Ids.append(l[1][y][0]) # get Random selection ID's from the list of all ID's random_IDs = [] while (random_IDs.__len__()<60): id = random.choice(Ids) if id not in random_IDs: random_IDs.append(id) # use the random ID's to populate a list of Fairies to build card deck from fairys = FairyImage.get_multiple_fairies_from_db("FAIRY_TBL", random_IDs) x = 0 pdf = StringIO.StringIO() c = canvas.Canvas(pdf, pagesize=PAGE_size) # Build the cards (DOn't know why multiples of 10? but this builds a deck of 54) while (x < 60): # fairy = FairyImage.get_fairy_from_db("FAIRY_TBL", int(Ids[x])) fairy = fairys[x] imgstring = fairy['image'] filelike = StringIO.StringIO(imgstring) pic = Image.open(filelike) # img = Image(filename=filelike, width=270, height=378) pic.thumbnail(IMG_size, Image.ANTIALIAS) c.drawInlineImage(pic, 5, 75, width=None, height=None) # Get Fairy Details name = fairy['name'] age = fairy['agescore'] kind = (int(fairy['kindscore'])/2) magic = fairy['magicscore'] agility = fairy['agilityscore'] charactor = fairy['charactorscore'] # define a large font c.setFont("Helvetica", 16) # choose some colors c.setStrokeColorRGB(0.2, 0.5, 0.3) # # draw some lines # c.line(0, 0, 0, 1.7 * inch) # c.line(0, 0, 1 * inch, 0) # draw a rectangle c.rect(0.1 * inch, 0.1 * inch, 180, 252, fill=0) # make text go straight up c.rotate(90) # change color c.setFillColorRGB(0, 0, 0.77) # say hello (note after rotate the y coord needs to be negative!) c.drawRightString(245, 0.4*-inch, str(name)) c.rotate(-90) # TODO set box to boy or girl colour c.setFillColorRGB(.9, .67, .98) c.rect(0.1 * inch, 0.1 * inch, 180, 1*inch, fill=1) c.setFont("Helvetica", 12) c.setFillColorRGB(0, 0, 0.77) c.drawString(0.2 * inch, 0.8 * inch, 'Age Index = '+ str(age)) c.drawString(0.2 * inch, 0.5 * inch, 'Kindness = '+ str(kind)) c.drawString(0.2 * inch, 0.2 * inch, 'Charactor = '+ str(charactor)) c.drawRightString(175, 0.8 * inch, 'Magic = '+ str(magic)) c.drawRightString(175, 0.5 * inch, 'Agility = '+ str(agility)) # table = Table(data, colWidths=180, rowHeights=252) # table.setStyle(TableStyle([ # # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # ('BOX', (0, 0), (-1, -1), 2, colors.palevioletred), # # ('BACKGROUND', (0, 0), (-1, 2), colors.lightgrey) # ])) # table.wrapOn(c, 0, 18) # table.drawOn(c, 0, 18) # c.showPage() x = x + 1 c.save() # Append all teh Cards into a PDF of all the cards for printing out input_pdf = PyPDF2.PdfFileReader(pdf) output_pdf = PyPDF2.PdfFileWriter() # calculate number of A4 paged reguired for 9 fairies per page error control to make sure it prints whole pages number_page = input_pdf.getNumPages() % 9 # get the first page from each pdf # start a new blank page with a size that can fit the merged pages side by side p = 0 while (p < number_page): page0 = input_pdf.pages[(9 * p) + 0] page1 = input_pdf.pages[(9 * p) + 1] page2 = input_pdf.pages[(9 * p) + 2] page3 = input_pdf.pages[(9 * p) + 3] page4 = input_pdf.pages[(9 * p) + 4] page5 = input_pdf.pages[(9 * p) + 5] page6 = input_pdf.pages[(9 * p) + 6] # page7 = input_pdf.pages[(9 * p) + 7] # page8 = input_pdf.pages[(9 * p) + 8] # page0 = input_pdf.pages[0] # page1 = input_pdf.pages[1] # page2 = input_pdf.pages[2] # page3 = input_pdf.pages[3] # page4 = input_pdf.pages[4] # page5 = input_pdf.pages[5] # page6 = input_pdf.pages[6] # page7 = input_pdf.pages[7] # page8 = input_pdf.pages[8] page = output_pdf.addBlankPage(width=595, height=843) page.mergeTranslatedPage(page0, 0, 0) page.mergeTranslatedPage(page1, 198, 0) page.mergeTranslatedPage(page2, 396, 0) page.mergeTranslatedPage(page3, 0, 273) page.mergeTranslatedPage(page4, 198, 273) page.mergeTranslatedPage(page5, 396, 273) page.mergeTranslatedPage(page6, 0, 546) # page.mergeTranslatedPage(page7, 198, 546) # page.mergeTranslatedPage(page8, 396, 546) p = p + 1 # write to file outputstream = StringIO.StringIO() output_pdf.write(outputstream) binary_pdf = outputstream.getvalue() outputstream.close() response = make_response(binary_pdf) response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] = \ 'inline; filename=%s.pdf' % 'test.pdf' return response
def topdf(path,recursion=None,pictureType=None,sizeMode=None,width=None,height=None,fit=None,save=None): """ Parameters ---------- path : string path of the pictures recursion : boolean None or False for no recursion True for recursion to children folder wether to recursion or not pictureType : list type of pictures,for example :jpg,png... sizeMode : int None or 0 for pdf's pagesize is the biggest of all the pictures 1 for pdf's pagesize is the min of all the pictures 2 for pdf's pagesize is the given value of width and height to choose how to determine the size of pdf width : int width of the pdf page height : int height of the pdf page fit : boolean None or False for fit the picture size to pagesize True for keep the size of the pictures wether to keep the picture size or not save : string path to save the pdf """ print path if platform.system() == 'Windows': path = path.replace('\\','/') if path[-1] != '/': path = (path + '/') print path if recursion == True: for i in os.listdir(path): if os.path.isdir(os.path.abspath(os.path.join(path, i))): topdf(path+i,recursion,pictureType,sizeMode,width,height,fit,save) filelist = [] if pictureType == None: filelist = glob.glob(os.path.join(path, '*.jpg')) else: for i in pictureType: filelist.extend(glob.glob(os.path.join(path, '*.'+i))) maxw = 0 maxh = 0 if sizeMode == None or sizeMode == 0: for i in filelist: print '----',i im = Image.open(i) if maxw < im.size[0]: maxw = im.size[0] if maxh < im.size[1]: maxh = im.size[1] elif sizeMode == 1: maxw = 999999 maxh = 999999 for i in filelist: im = Image.open(i) if maxw > im.size[0]: maxw = im.size[0] if maxh > im.size[1]: maxh = im.size[1] else: if width == None or height == None: raise Exception("no width or height provid") maxw = width maxh = height maxsize = (maxw,maxh) if save == None: filename_pdf = path + path.split('/')[-2] else: filename_pdf = save + path.split('/')[-2] filename_pdf = filename_pdf.decode('utf8','ignore') filename_pdf = filename_pdf + '.pdf' print filename_pdf c = canvas.Canvas(filename_pdf, pagesize=maxsize ) l = len(filelist) for i in range(l): print filelist[i] (w, h) =maxsize width, height = letter if fit == True: c.drawImage(filelist[i] , 0,0) else: c.drawImage(filelist[i] , 0,0,maxw,maxh) c.showPage() c.save() print "end."