def verdmidar(vorur): """ Býr til PDF skjal af verðmiðum úr lista af Vörum. """ import labels from reportlab.graphics import shapes from reportlab.pdfbase.pdfmetrics import stringWidth # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, vara): textastaerd = 32 nafnbreidd = stringWidth(vara.fulltnafn, "Helvetica", textastaerd) while nafnbreidd > width - 4: textastaerd *= 0.95 nafnbreidd = stringWidth(vara.fulltnafn, "Helvetica", textastaerd) nafnbreidd = stringWidth(vara.fulltnafn, "Helvetica", textastaerd) label.add( shapes.String((width - nafnbreidd) / 2, height - 32 - 16, str(vara.fulltnafn), fontName="Helvetica", fontSize=textastaerd)) label.add( shapes.String(2, 2, str(vara.verd().smasoluverd) + ' kr.', fontName="Helvetica", fontSize=16)) label.add( shapes.String(width - 2, 2, str(vara.vorunumer()), fontName="Helvetica", fontSize=16, textAnchor="end")) # Create the sheet. #sheet = labels.Sheet(specs, draw_label, border=False) sheet = labels.Sheet(specs, draw_label) # Add a couple of labels. for vara in vorur: sheet.add_label(vara) print(vara.verd()) #print(vara.verd) # Save the file and we are done. sheet.save('basic.pdf') print("{0:d} label(s) output on {1:d} page(s).".format( sheet.label_count, sheet.page_count))
def download_medal_labels(request): specs = labels.Specification(215.9, 279.4, 4, 5, 38.1, 38.1, corner_radius=19.0, top_margin=20, bottom_margin=20) sheet = labels.Sheet(specs, draw_medal_label, border=False) medal_labels = [] for division in models.Division.objects.all(): # Event Awards for event in models.Event.objects.all(): for place in range(division.event_award_count): medal_labels.append({ 'meet': division.meet.short_name, 'session': division.session.first().name, 'level': 'Level: {}'.format(division.level.name.upper()), 'age_div': 'Div: {}'.format(division.short_name), 'place': '{} Place'.format(ordinal(place + 1)), 'event': event.name, }) # All Around Awards, skipping 1st-3rd place if division.all_around_award_count > 3: for place in range(4, division.all_around_award_count + 1): medal_labels.append({ 'meet': division.meet.short_name, 'session': division.session.first().name, 'level': 'Level: {}'.format(division.level.name.upper()), 'age_div': 'Div: {}'.format(division.short_name), 'place': '{} Place'.format(ordinal(place)), 'event': 'All Around', }) sheet.add_labels(medal_labels) timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M') response = HttpResponse(content_type='applicaiton/pdf') response[ 'content-Disposition'] = 'attachment;filename=medal_labels_' + timestamp + '.pdf' sheet.save(response) return response
def create_pdf(db, ids): specs = labels.Specification(57, 32, 1, 2, 57, 16) sheet = labels.Sheet(specs, _draw_label, border=True) for i in ids: item = _query_by(db, Item, 'id', i) project = _query_by(db, Project, 'name', item.project_name) sheet.add_label((item, project)) sheet.save('tmp/label.pdf') return 'label.pdf'
def createAvery5160Spec(): f = 25.4 # conversion factor from inch to mm # Compulsory arguments. sheet_width = 8.5 * f sheet_height = 11.0 * f columns = 3 rows = 10 label_width = 2.63 * f label_height = 1.00 * f # Optional arguments; missing ones will be computed later. left_margin = 0.19 * f column_gap = 0.12 * f right_margin = 0 top_margin = 0.50 * f row_gap = 0 bottom_margin = 0 # Optional arguments with default values. left_padding = 1 right_padding = 1 top_padding = 1 bottom_padding = 1 corner_radius = 2 padding_radius = 0 background_filename = "bg.png" #specs = labels.Specification(210, 297, 3, 8, 65, 25, corner_radius=2) # units = mm ! specs = labels.Specification( sheet_width, sheet_height, columns, rows, label_width, label_height, left_margin=left_margin, column_gap=column_gap, # right_margin = right_margin , top_margin=top_margin, row_gap=row_gap, # bottom_margin = bottom_margin , left_padding=left_padding, right_padding=right_padding, top_padding=top_padding, bottom_padding=bottom_padding, corner_radius=corner_radius, padding_radius=padding_radius, #background_filename=background_filename, ) return specs
def codes2pdf(codes, batch_id): specs = labels.Specification(210, 297, 3, 10, 65, 25, corner_radius=2, bottom_padding=5) sheet = labels.Sheet(specs, draw_label, border=True) for code in codes: sheet.add_label(code) filename = str(batch_id) + '.pdf' sheet.save(filename) print("{0:d} label(s) output on {1:d} page(s).".format( sheet.label_count, sheet.page_count))
def generate_labels(): mailingInfo = run_scraper() specs = labels.Specification(215.9, 279.4, 3, 10, 66.7, 25.4, corner_radius=2) sheet = labels.Sheet(specs, drawLabel, border=True) sheet.add_labels(mailingInfo) sheet.save('mailing_labels.pdf') print('done!')
def get_sheet(): # Avery 5963 Labels # http://www.avery.com/avery/en_us/Products/Labels/Shipping-Labels/White-Shipping--Labels_05963.htm # http://www.worldlabel.com/Pages/wl-ol125.htm specs = labels.Specification(216, 279, 2, 5, 102, 51, corner_radius=2, left_padding=3, bottom_padding=2, row_gap=0) # Add some fonts. registerFont(TTFont('Judson Bold', os.path.join(base_path, 'Judson-Bold.ttf'))) registerFont(TTFont('KatamotzIkasi', os.path.join(base_path, 'KatamotzIkasi.ttf'))) # Create the sheet. return labels.Sheet(specs, write_name, border=False)
def get_specification(self): """Return the labels.Specification for this spec. """ self.ensure_one() return labels.Specification( self.sheet_width, self.sheet_height, self.num_columns, self.num_rows, self.label_width, self.label_height, corner_radius=self.label_corner_radius, column_gap=self.column_gap, row_gap=self.row_gap, left_padding=self.label_left_padding, right_padding=self.label_right_padding, top_padding=self.label_top_padding, bottom_padding=self.label_bottom_padding, )
def create_label_spec(): """Create a label specification with 3x10 labels per sheet. Tested against Avery 8160 (Avery 5160 template). """ # The labels library takes measurements in millimeters (1 inch = 25.4 mm). return labels.Specification( sheet_width=215.9, # 8 1/2" sheet_height=279.4, # 11" rows=10, columns=3, label_width=66.669, # 2 5/8" label_height=25.4, # 1" left_margin=4, column_gap=4, top_margin=12, row_gap=0, corner_radius=2, )
def download_athlete_labels(request): gymnasts = models.Gymnast.objects.all().\ exclude(is_scratched=True, athlete_id=None).\ order_by('division__session', 'team', 'division', 'last_name', 'first_name').\ select_related() specs = labels.Specification(215.9, 279.4, 3, 10, 66.675, 25.4, row_gap=0, corner_radius=2, left_margin=5, right_margin=5) sheet = labels.Sheet(specs, draw_athlete_label, border=False) athlete_labels = [] for gymnast in gymnasts: session = 'None' if gymnast.division and gymnast.division.session.first(): session = gymnast.division.session.first().name label = {} label['id'] = str(gymnast.athlete_id) label['name'] = '{} {}'.format(gymnast.first_name, gymnast.last_name) label['team'] = gymnast.team.team label['info'] = '{2} Level: {0} Div: {1}'.format( gymnast.level.name.upper(), gymnast.division.short_name if gymnast.division else '', session) athlete_labels.append(label) sheet.add_labels(athlete_labels) timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M') response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment;filename=athlete_labels_' + timestamp + '.pdf' sheet.save(response) return response
def create_labels(folder='invitations/scripts/labels/'): def draw_label(label, width, height, obj): label.add( shapes.String(2, 2, str(obj), fontName='Helvetica', fontSize=10)) specs = labels.Specification(215.9, 279.4, 2, 5, 101.6, 50.8, corner_radius=2) guests = Guest.objects.invited().filter(country='US') for page_num, page in enumerate(chunks(guests, size=10)): sheet = labels.Sheet(specs, draw_label, border=True) for guest in page: text = f'{guest.party_line()}\n' text += '\r'.join(guest.address()) sheet.add_label(text) sheet.save(os.path.join(folder, f'label_sheet_{page_num:02}.pdf'))
def download_team_labels(request): sessions = models.Session.objects.all() specs = labels.Specification(215.9, 279.4, 3, 10, 66.675, 25.4, row_gap=0, corner_radius=2, left_margin=5, right_margin=5) sheet = labels.Sheet(specs, draw_team_label, border=False) team_labels = [] for session in sessions: levels = ', '.join(map(str, sorted(session.levels))) teams = Team.objects.filter(gymnasts__division__session=session).\ order_by('gymnasts__division__session', 'team').distinct() for team in teams: team_labels.append({ 'team': team.team, 'session': session.name, 'level': 'Level: {}'.format(levels.upper()) }) sheet.add_labels(team_labels) timestamp = datetime.now().strftime('%Y-%m-%d-%H-%M') response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment;filename=team_labels_' + timestamp + '.pdf' sheet.save(response) return response
# Install these modules before first time running script. import labels, openpyxl from openpyxl.utils import get_column_letter, column_index_from_string from reportlab.graphics import shapes from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth # Python standard modules. import sys, os, warnings, re, math warnings.simplefilter("ignore") # Letter size sheet (215.9mm x 279.4mm) with Avery 5160 labels. # 3 columns and 10 rows with labels of size 101.6mm x 50.8mm and a 2mm corner radius. # The margins are as per specifications from the manufacturer. specs = labels.Specification(215.9, 279.4, 3, 10, 66.8, 25.4, corner_radius=2, left_padding=1, top_padding=1, bottom_padding=1, right_padding=1, padding_radius=0, left_margin=4.8, column_gap=3, top_margin=12.7, row_gap=0) # Get the path to the current directory. base_path = os.path.dirname(sys.argv[0]) os.chdir(base_path) # Add some fonts. registerFont(TTFont('Calibri', os.path.join(base_path, 'calibri.ttf'))) registerFont(TTFont('Calibrib', os.path.join(base_path, 'calibrib.ttf'))) registerFont(TTFont('Calibrii', os.path.join(base_path, 'calibrii.ttf'))) # Opens sheet with the data, determines the last row, and creates save file name. def export_file_processor(exportFile): while os.path.isfile(exportFile) == False:
from reportlab.graphics.barcode import eanbc import qrcode from tempfile import mktemp # Configuration LABEL_USE = "a_61533" # Type of label LABEL_SETS = {'C': 120, 'S': 240} # Label prefixes and counts LABEL_TYPE = { "a_5963": labels.Specification(210, 297, 2, 5, 102, 54, corner_radius=2, top_margin=8, row_gap=2, left_margin=0, right_margin=0), "a_5267": labels.Specification(210, 297, 4, 20, 47, 14, corner_radius=2, top_margin=8, row_gap=0,
# Note that any oversize label is automatically trimmed to prevent it messing up # other labels. sheet.add_label("Oversized label here") # Save the file and we are done. sheet.save(filename) print("{0:s}: {1:d} label(s) output on {2:d} page(s).".format( filename, sheet.label_count, sheet.page_count)) # Option one: background from a file. specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2, background_filename=file1) process_sheet(specs, "page_background_file.pdf") # Option two: background from a ReportLab image. # Note we just load it from file, but you could do something fancier... # The size parameters don't matter as pylabels will scale it to fit the page. specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2,
# A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # pylabels. If not, see <http://www.gnu.org/licenses/>. # Very basic test script to generate labels, based on the PyLabels library. import labels from reportlab.lib.units import mm from reportlab.graphics import shapes from reportlab.graphics.barcode import qr # Create a portrait label for use with Zebra LP 2844 (101.6mm x 101.6mm) sheets with 1 columns and 1 row of # labels. Each label is 90mm x 25mm with a 1mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(101.6, 101.6, 1, 1, 100, 100, corner_radius=1) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. label.add( shapes.String(5, 260, "MK Makerspace Project", fontName="Helvetica", fontSize=20)) label.add(
conn = sqlite3.connect('inventory.db') cur = conn.cursor() # nsn, pn, desc, remarks, location, niin, acft db = cur.execute('select desc, pn, location, niin, nsn, acft from benchstock where acft="apache"').fetchall() font_path = 'fonts' big_lablels = (101, 34, 2, 7) address_labels = (68.675, 26.4, 3, 10) label_width , label_height, columns, rows = address_labels # registerFont(TTFont('3of9', os.path.join(font_path, 'free3of9.ttf'))) # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. # 215.9 by 279.4 mm specs = labels.Specification(215,279.4, columns, rows, label_width, label_height, row_gap=0, column_gap=4,top_padding=1, bottom_padding=1, right_padding=1) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label_top_bc(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. label.add(shapes.String(2, 2, str(obj[0]), fontName="Helvetica", fontSize=12)) label.add(shapes.String(2, 13, str(obj[1]), fontName="Helvetica", fontSize=12 )) label.add(shapes.String(2, 24, str(obj[2]), fontName="Helvetica", fontSize=12)) label.add(shapes.Image(2, 46, 180, 40, make_barcode(obj[3], obj[5]))) # label.add(shapes.String(38, 30, str(obj[3]), fontName="3of9", fontSize=30)) label.add(shapes.String(2, 35, str(obj[4]), fontName="Helvetica", fontSize=12)) # def draw_label_btm_bc(label, width, height, obj):
def gen_nametags(competition_name, persons): ### Initialize font registerFont(TTFont('Trebuchet', NAMETAG_FONT_PATH)) # Format information for nametags: DIN-A4 layout with 2 rows of 4 nametags each with a size of 85x55mm specs = labels.Specification(210, 297, 2, 4, 85, 55) # Local function for nametag layout. Heavily uses add_text_field and is passed to sheet creation # obj is one list element of persons, i.e. one dict from utils/data_from_WCIF.get_nametag_data() def create_nametag(label, width, height, obj): competition_name = obj[0] person = obj[1] # Write competition name, competitor name and nation add_text_field(label, competition_name, width / 2.0, height - 25, max_width=width - 5, max_font_size=50, font="Helvetica") name = person['name'] # Add delegate / organizer color if person['delegate']: name_color = colors.red name = name + " (Delegate)" # Eventually replace with elif person['organizer']: name_color = colors.red name = name + " (Orga)" # emoji support (see constants at top of file) else: name_color = colors.black add_text_field(label, name, width / 2.0, height / 2.0, max_width=width - 5, max_font_size=25, color=name_color) add_text_field(label, person['nation'], width / 2.0, height / 3.0, max_width=150, max_font_size=20, color=colors.black) if person['wcaId'] == None: # Add newcomer label add_text_field(label, "Newcomer!", width / 2.0, FOOTER_HEIGHT, font_size=30, color=colors.green) else: # Add 3x3 PBs, comp_count and Best if person['_3x3']['single'] != -1 and person['_3x3'][ 'average'] != -1: rubiks_text = "3x3 PBs: {} S / {} A".format( format_result(person['_3x3']['single']), format_result(person['_3x3']['average'])) if (person['best']['eventName'] != '3x3x3'): add_text_field(label, rubiks_text, FOOTER_SIDE_MARGIN, FOOTER_HEIGHT + 10, font_size=10, color=colors.blue, position="start") best_text = "Best World Ranking: {} ({} {} of {})".format( person['best']['ranking'], person['best']['eventName'], person['best']['type'], format_result(person['best']['result'], person['best']['eventName'])) add_text_field(label, best_text, FOOTER_SIDE_MARGIN, FOOTER_HEIGHT, max_width=width - 20, max_font_size=10, color=colors.blue, position="start") comp_count = "Competition # " + str(person['numComps'] + 1) add_text_field(label, comp_count, width - FOOTER_SIDE_MARGIN, FOOTER_HEIGHT + 10, font_size=10, color=colors.blue, position="end") # Create the sheet and add labels sheet = labels.Sheet(specs, create_nametag, border=True) sheet.add_labels((competition_name, person) for person in persons) # Check if folder is there or create, and safe in folder competition_name_stripped = competition_name.replace(" ", "") if not os.path.exists(competition_name_stripped): os.makedirs(competition_name_stripped) nametag_file = competition_name_stripped + '/Nametags.pdf' sheet.save(nametag_file) print("{0:d} nametags output on {1:d} pages.".format( sheet.label_count, sheet.page_count))
twitter_history = pickle.load(fp) # df = pd.DataFrame.from_csv('master.csv', encoding = "utf-8") df = pd.read_excel('master.xlsx') _l = [] # for t in twitter_history: for t in df['full_text']: _l.append(text2paragraph(t)) specs = labels.Specification(297, 210, 5, 5, 59, 38.8, corner_radius=0, top_margin=7.5, left_margin=1, row_gap=0.25, column_gap=0) # worldcontrol = api.search(q = "@truWorldControl", tweet_mode='extended') # since_id = worldcontrol[1].id # since_id = None since_id = twitter_history[0]['id'] def create_pdf(tweet): global _l logger.info("Create PDF")
import csv import argparse from reportlab.graphics import shapes from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth # On attend en entrée le nom d'un cvs parser = argparse.ArgumentParser(description='Generateur d\'etiquettes') parser.add_argument('-i','--input', help='fichier csv en entree',required=True) args = parser.parse_args() # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(210, 297, 2, 6, 99, 42.3, top_margin=21.5, row_gap=0) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. Prenom = obj[0] Nom = obj[1] Entreprise = obj[2] Email = obj[3] Tel = obj[4] # Measure the width of the first name and shrink the font size until it fits. prenom_font_size = 14
wd # In[6]: # Encode the urn as a QR code; use the last six characters as a human-readable label to name the file for tpl in l_contents: machine, human = tpl qr = segno.make_qr(machine) qr.save(os.path.join(wd, f"{human}.png"), scale=3, background=None) # ### Set up label page # In[7]: specs = labels.Specification(215.9, 279.4, 2, 3, 95.25, 76.2) # In[8]: def write_content(label, width, height, filepath): # Create a shape for the QR code image and position it im = Image.open(filepath) imwidth, imheight = im.size a = shapes.Image(((width / 2.0) - (imwidth / 2.0)), 45, imwidth, imheight, filepath) # Create a human-readable label and position it human_readable = os.path.splitext(os.path.split(filepath)[1])[0] b = shapes.String(width / 2.0, 15, human_readable, textAnchor="middle")
# version. # # pylabels is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # pylabels. If not, see <http://www.gnu.org/licenses/>. import labels from reportlab.graphics import shapes # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(210, 297, 2, 3, 103, 79) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. label.add(shapes.String(2, 2, str(obj), fontName="Helvetica", fontSize=40)) # Create the sheet. sheet = labels.Sheet(specs, draw_label, border=True) # Add a couple of labels. sheet.add_label("Hello") sheet.add_label("World")
label.add(s) # config variables pardir = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) config = configparser.ConfigParser() config.read(pardir + "\Step_2_config.txt") filesToProcess = json.loads(config.get("CONFIG", "filesToProcess")) # Create A4 portrait (210mm x 297mm) sheets with labels. specs = labels.Specification( sheet_width=210, # A4 sheet_height=297, # A4 columns=(config["CONFIG"]["columns"]), rows=(config["CONFIG"]["rows"]), label_width=(config["CONFIG"]["label_width"]), label_height=(config["CONFIG"]["label_height"]), corner_radius=2, ) for countryFile in filesToProcess: # Create the sheet with or without border sheet = labels.Sheet(specs, writeLabelInfo, border=False) # get address data from spreadsheet wb = xlrd.open_workbook(pardir + "\\" + countryFile) ws = wb.sheet_by_index(0) allInfo = [] rowInfo = []
# version. # # pylabels is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # pylabels. If not, see <http://www.gnu.org/licenses/>. import labels from reportlab.graphics import shapes # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. label.add(shapes.String(2, 2, str(obj), fontName="Helvetica", fontSize=40)) # Create the sheet. sheet = labels.Sheet(specs, draw_label, border=True) # Mark some of the labels on the first page as already used.
def label_maker(acft): """ Makes labels for my inventory program""" conn = sqlite3.connect('inventory.db') cur = conn.cursor() # nsn, pn, desc, remarks, location, niin, acft db = cur.execute( 'select desc, pn, location, niin, nsn, acft from benchstock where acft="{}" and label="true"' .format(acft)).fetchall() font_path = 'fonts' big_lablels = (101, 34, 2, 7) address_labels = (68.675, 26.4, 3, 10) label_width, label_height, columns, rows = address_labels specs = labels.Specification(215, 279.4, columns, rows, label_width, label_height, row_gap=0, column_gap=4, top_padding=1, bottom_padding=1, right_padding=1) def draw_label_top_bc(label, width, height, obj): # Just convert the object to a string and print this at the bottom left of # the label. label.add( shapes.String(2, 2, str(obj[0]), fontName="Helvetica", fontSize=12)) label.add( shapes.String(2, 13, str(obj[1]), fontName="Helvetica", fontSize=12)) label.add( shapes.String(2, 24, str(obj[2]), fontName="Helvetica", fontSize=12)) label.add(shapes.Image(2, 46, 180, 40, make_barcode(obj[3]))) # label.add(shapes.String(38, 30, str(obj[3]), fontName="3of9", fontSize=30)) label.add( shapes.String(2, 35, str(obj[4]), fontName="Helvetica", fontSize=12)) def make_barcode(code): leading = '000' if acft == 'luh': leading = '720' elif acft == 'apache': leading = '640' code = leading + str(code) ean = barcode.get('ean13', code, writer=ImageWriter()) filename = ean.save('barcodes/{}'.format(code)) return filename sheet = labels.Sheet(specs, draw_label_top_bc, border=False) s = '1234121231234' n = '{}-{}-{}-{}'.format(s[:-9], s[-9:-7], s[-7:-4], s[-4:]) # sheet.add_label([ 'Nomenclature','Part No.', 'Location', '1234121231234',n, '']) for row in db: if row[3] != '': nsn = '{}-{}-{}-{}'.format(row[4][:-9], row[4][-9:-7], row[4][-7:-4], row[4][-4:]) sheet.add_label([row[0], row[1], row[2], row[3], nsn, row[5]]) sheet.save('basic_new.pdf') print("{0:d} label(s) output on {1:d} page(s).".format( sheet.label_count, sheet.page_count))
import csv import labels from reportlab.graphics import shapes # Createa a labels page, matching Avery 5160, 8160, 6240, etc. PADDING = 1 specs = labels.Specification(215.9, 279.4, 3, 10, 64, 25.4, corner_radius=2, left_margin=5, right_margin=5, top_margin=13, left_padding=PADDING, right_padding=PADDING, top_padding=PADDING, bottom_padding=PADDING, row_gap=0) Address = namedtuple( 'Address', ['name', 'name2', 'street1', 'street2', 'city', 'state', 'zip']) def draw_address(label, width, height, address): assert address.state, address assert address.zip, address
import json from reportlab.graphics import shapes from reportlab.graphics.charts.textlabels import Label from reportlab.lib.units import cm, mm, inch, pica import labels BORDER=False specs = labels.Specification(216, 279, 3, 10, 66, 25, corner_radius=2, left_margin=6, right_margin=4, column_gap=4, top_margin=15, bottom_margin=14, row_gap=0, ) def load_people(filename='people.json'): with open('people.json', 'r') as infile: return json.load(infile) # 215.9 by 279.4 def write_label(label, width, height, person): text = "\n".join((person['name'], person['addresses'][0])) lab = Label() lab.setOrigin(8, height - 5) lab.fontSize = 14 lab.setText(text) lab.boxAnchor = 'nw'
else: print("Something went wrong with the JSON request") sys.exit(1) # Create an A4 portrait (210mm x 297mm) sheets with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. # Create an A4 portrait (210mm x 297mm) sheet, with an envelope outline in # the top center part, the envelope is 95mm wide, 145mm long. It's situated # 2mm from the top and, 59mm from each side (59+145+59~=210mm) specs = labels.Specification(210, 297, 1, 1, 95, 145, left_margin=59, top_margin=2) base_path = os.path.dirname(__file__) # I like this font but it's not distributed with this script, if you have # a windows install you can find it there or replace this with your own. registerFont(TTFont('Consolas Bold', os.path.join(base_path, 'Consolas.ttf'))) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. Refer to: # Chapter 11: Graphics of the ReportLab UserGuide
colors.HexColor(0x04F1B1), colors.HexColor('#ADADAF'), colors.Color(0.5, 0.1, 0.7), colors.Color(0.5, 0.1, 0.1, alpha=0.5), colors.CMYKColor(0.1, 0.1, 0.6, 0.3), ] # Create an A4 portrait (210mm x 297mm) sheet with 2 columns and 8 rows of # labels. Each label is 90mm x 25mm with a 2mm rounded corner. The margins are # automatically calculated. specs = labels.Specification(210, 297, 2, 8, 90, 25, corner_radius=2, left_padding=5, top_padding=5, bottom_padding=5, right_padding=10, padding_radius=4) # Create a function to draw each label. This will be given the ReportLab drawing # object to draw on, the dimensions (NB. these will be in points, the unit # ReportLab uses) of the label, and the object to render. def draw_label(label, width, height, obj): # Pick a background colour. colour = random.choice(colours) # And a style.
def handle_noargs(self, **options): # Get the cages prompt = ('Enter a list of cage names, separated by spaces, for' 'which you need water restriction labels.\n' 'Example: CR22 CR12 CR13\n') data = raw_input(prompt) water_restriction_cage_name_l = data.split() prompt = ('Enter a list of cage names, separated by spaces, for' 'which you need cage labels.\n' 'Example: CR22 CR12 CR13\n') data = raw_input(prompt) cage_card_cage_name_l = data.split() prompt = ('Enter the row to start printing on. Example: for the ' 'second from top row, enter 2: ') data = raw_input(prompt) row_start = int(data) specs = labels.Specification(215.9, 279.4, 2, 15, 87.3, 16.9, corner_radius=2, row_gap=0, column_gap=13.3) def draw_label(label, width, height, obj): print obj try: fillColor = obj['fillColor'] except KeyError: fillColor = 'black' kwargs = { 'fontName': 'Helvetica', 'fontSize': 10, 'textAnchor': 'middle', 'fillColor': fillColor } if obj['typ'] == 'water restriction': kwargs = { 'fontName': 'Helvetica', 'fontSize': 10, 'textAnchor': 'middle', 'fillColor': fillColor } ## Header label.add( shapes.String( width * .5, height - 10, "WATER RESTRICTED -- Cage %s" % obj['cage_name'], **kwargs)) label.add( shapes.String(width * .5, height - 20, "BRUNO LAB AAAY8462 UNI: CCR2137", **kwargs)) label.add( shapes.Line(width * .02, height - 22, width * .98, height - 22, strokeColor=fillColor)) ## Each mouse xy_l = [(.2, -32), (.5, -32), (.8, -32), (.2, -42), (.5, -42), (.8, -42)] for mouse, headplate, xy in zip(obj['mice'], obj['headplates'], xy_l): label.add( shapes.String(width * xy[0], height + xy[1], '%s - %s' % (mouse, headplate), **kwargs)) elif obj['typ'] == 'cage': kwargs = { 'fontName': 'Helvetica', 'fontSize': 10, 'textAnchor': 'start', 'fillColor': fillColor } ## Header label.add( shapes.String(width * .5, height - 10, "Cage: %s" % obj['cage_name'], fontName='Helvetica', fontSize=10, fillColor=fillColor, textAnchor='middle')) ## Each mouse xy_l = [(.1, -20), (.6, -20), (.1, -30), (.6, -30), (.1, -40)] for mouse, full_name, genotype, headplate, xy in zip( obj['mice'], obj['full_names'], obj['genotypes'], obj['headplates'], xy_l): label.add( shapes.String( width * xy[0], height + xy[1], '%s - %s - %s' % (mouse, headplate, full_name), **kwargs)) # Directly specify the cages we need cage_name_l = water_restriction_cage_name_l + cage_card_cage_name_l cage_name_l = list(np.unique(cage_name_l)) # Get the colony specs colony_specs = {} for cage_name in cage_name_l: # Init the specs for this cage colony_specs[cage_name] = {} colony_specs[cage_name]['mice'] = [] colony_specs[cage_name]['headplates'] = [] colony_specs[cage_name]['genotypes'] = [] colony_specs[cage_name]['full_names'] = [] colony_specs[cage_name]['cage_name'] = cage_name # Find the cage cage = runner.models.BehaviorCage.objects.filter( name=cage_name).first() # Set the color colony_specs[cage_name]['fillColor'] = cage.label_color.lower() if colony_specs[cage_name]['fillColor'] == 'pink': colony_specs[cage_name]['fillColor'] = 'magenta' # Iterate over mice for mouse in cage.mouse_set.all(): colony_specs[cage_name]['mice'].append(mouse.name) colony_specs[cage_name]['headplates'].append( mouse.headplate_color) colony_specs[cage_name]['genotypes'].append(mouse.genotype) colony_specs[cage_name]['full_names'].append( mouse.husbandry_name) # Make a sheet sheet = labels.Sheet(specs, draw_label, border=False) # Define the used labels used_labels = [] for row in range( 1, row_start): # second number is the 1-based row to start on for col in range(1, 3): used_labels.append((row, col)) sheet.partial_page(1, used_labels) # Add label for each cage for cage_name, cage_specs in colony_specs.items(): if cage_name in water_restriction_cage_name_l: # Copy specs over cage_specs2 = cage_specs.copy() cage_specs2['typ'] = 'water restriction' # Add the label sheet.add_label(cage_specs2) if cage_name in cage_card_cage_name_l: # Copy specs over cage_specs2 = cage_specs.copy() cage_specs2['typ'] = 'cage' # Add the label sheet.add_label(cage_specs2) sheet.save("auto_created_labels.pdf") os.system('xdg-open auto_created_labels.pdf')