def buildPDF(self, data, document_root): data = json.loads(data)[0]['fields'] content = StringIO.StringIO() parser = canvas.Canvas(content, pagesize=letter) self.employee_name(parser, data['name']) self.social_security(parser, data['ssn']) self.title(parser, data['title']) self.base_salary(parser, data['base_salary']) self.period(parser, data['period']) self.period_year(parser, data['period_year']) self.effective_date(parser, data['effective_date']) self.multi_campus(parser, data['multi_campus']) self.sponsored_accounts(parser, data['sponsored_accounts']) self.cost_sharing(parser, data['cost_sharing']) self.university_funds(parser, data['university_funds']) self.payments_paid(parser, data['payments_paid']) self.comments(parser, data['comments']) parser.save() content.seek(0) text = PdfFileReader(content) form = PdfFileReader(document_root+'/a125.pdf').getPage(0) output = PdfFileWriter() form.mergePage(text.getPage(0)) output.addPage(form) outputStream = open(document_root+'/a125-gen.pdf', 'wb') output.write(outputStream) self.form = output
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 gen_pdf(quantity=1, frame='A4', type='0', numbered=false): """ Generates a PDF document. Generates a PDF document depending on the quantity of pages, the template type and the page size. Parameters ---------- quantity : int The number of pages that will contain the document. frame : str The size of the page, it can be A4 or Letter. type : str A string number that refers to the type of page, it can be (DotGrid:0, Graph:1, Lined:2, Music:3). numbered : bool Define if the pages will be numbered or not. Returns ------- str Returns a message with the status """ # Looks for the qr code letter frame = frame.lower().capitalize() code = TYPES[type][1][frame] # Looks for the template type String type = TYPES[type][0] out_file = OUTPUT_FILENAME.format(frame, type, quantity) if os.path.exists(out_file): return "The file %s already exists" % out_file path = PATH.format('/%s/%s' % (frame, type)) frame_class = class_for_name("reportlab.lib.pagesizes", frame.upper()) pathlib.Path(path).mkdir(parents=True, exist_ok=True) output = PdfFileWriter() for num in range(1, int(quantity) + 1): # Adjust for the 1 start # Using ReportLab Canvas to insert image into PDF imgTemp = BytesIO() imgDoc = canvas.Canvas(imgTemp, pagesize=frame_class) # Draw image on Canvas and save PDF in buffer imgDoc.drawImage(qr_generate(num, path, code), int(POSITION[frame][0]), int(POSITION[frame][1])) if numbered: imgDoc.drawRightString( int(POSITION[frame][0]) - 7, int(POSITION[frame][1]) + 3, str(num)) imgDoc.save() # Select PageToMerge pageToMerge = PdfFileReader(open(TEMPLATE.format(frame, type), "rb")).getPage(0) #pageToMerge = PdfFileReader(open(TEMPLATE, "rb")).getPage(0) pageToMerge.mergePage( PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0)) output.addPage(pageToMerge) # finally, write "output" outputStream = open(out_file, "wb") output.write(outputStream) outputStream.close() return "The file %s was created" % out_file
def generate_postcard(customer): pdfmetrics.registerFont(HOOKCOFFEE_CLUB) greeting = 'HOLA %s !' % customer.first_name greeting_position = (475, 1300) postcard = Postcard.objects.latest('id').customer_postcard template_src = os.path.join(settings.MEDIA_ROOT, str(postcard)) buffer = StringIO() c = canvas.Canvas(buffer) c.setLineWidth(.3) c.setFont('HookCoffeeClub', 96) x, y = greeting_position c.drawCentredString(x, y, greeting) c.showPage() c.save() page = PdfFileReader(file(template_src, 'rb')).getPage(0) overlay = PdfFileReader(StringIO(buffer.getvalue())).getPage(0) page.mergePage(overlay) return page
def gen_pdf(quantity=1, frame='A4', type='0', numbered=false): """ Generates a PDF document. Generates a PDF document depending on the quantity of pages, the template type and the page size. Parameters ---------- quantity : int The number of pages that will contain the document. frame : str The size of the page, it can be A4 or Letter. type : str A string number that refers to the type of page, it can be (DotGrid:0, Graph:1, Lined:2, Music:3). numbered : bool Define if the pages will be numbered or not. Returns ------- str Returns a message with the status """ # Looks for the qr code letter frame = frame.lower().capitalize() code = TYPES[type][1][frame] # Looks for the template type String type = TYPES[type][0] out_file = OUTPUT_FILENAME.format(frame, type, quantity) if os.path.exists(out_file): return "The file %s already exists" % out_file path = PATH.format('/%s/%s' % (frame, type)) frame_class = class_for_name("reportlab.lib.pagesizes", frame.upper()) pathlib.Path(path).mkdir(parents=True, exist_ok=True) output = PdfFileWriter() for num in range(1, int(quantity)+1): # Adjust for the 1 start # Using ReportLab Canvas to insert image into PDF imgTemp = BytesIO() imgDoc = canvas.Canvas(imgTemp, pagesize=frame_class) # Draw image on Canvas and save PDF in buffer imgDoc.drawImage(qr_generate(num, path, code), int(POSITION[frame][0]), int(POSITION[frame][1])) if numbered: imgDoc.drawRightString(int(POSITION[frame][0])-7, int(POSITION[frame][1])+3, str(num)) imgDoc.save() # Select PageToMerge pageToMerge = PdfFileReader(open(TEMPLATE.format(frame, type), "rb")).getPage(0) #pageToMerge = PdfFileReader(open(TEMPLATE, "rb")).getPage(0) pageToMerge.mergePage(PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0)) output.addPage(pageToMerge) # finally, write "output" outputStream = open(out_file, "wb") output.write(outputStream) outputStream.close() return "The file %s was created" % out_file
def pdfMerger(pdfs_in, pdf_out, path=''): ''' Merge multiple PDF files together ''' output = PdfFileWriter() main_pdf = PdfFileReader(open(pdfs_in[0], "rb")).getPage(0) for i in range(1, len(pdfs_in)): pdf = PdfFileReader(open(pdfs_in[1], "rb")).getPage(0) main_pdf.mergePage(pdf) output.addPage(main_pdf) output.write(open(path + pdf_out, "wb"))
def merge_pdfs(target, image, output): with open(target, 'rb') as template, open(image, 'rb') as overlay: template_pdf = PdfFileReader(template).getPage(0) overlay_pdf = PdfFileReader(overlay).getPage(0) writer = PdfFileWriter() template_pdf.mergePage(overlay_pdf) # add page from input file to output document writer.addPage(template_pdf) with open(output, "wb") as outputStream: writer.write(outputStream)
def merge_pdf(self, nome): from PyPDF2 import PdfFileReader, PdfFileWriter import os pasta = 'static/faturas/' if not os.path.exists(pasta): os.makedirs(pasta) tmp = PdfFileReader('static/template.pdf').getPage(0) tmp.mergePage(PdfFileReader('db/dados.pdf').getPage(0)) fatura = PdfFileWriter() fatura.addPage(tmp) file = pasta + nome with open(file, 'wb') as fh: fatura.write(fh)
def add_label_to_file( original_file: str, new_file: str, label_string: str, ): with open(original_file, "rb") as orig, \ open(new_file, "wb") as new: original_page = PdfFileReader(orig).getPage(0) label_page = generate_label_page(label_string) original_page.mergePage(label_page) output_pdf = PdfFileWriter() output_pdf.addPage(original_page) output_pdf.write(new)
class PdfEditor(object): '''Class for modifying a previously existing PDF's. note:: Currently only works 1 page PDF's. Origin is on LOWER left corner. ''' def __init__(self, filename, pageSize, strict=True): '''Args: filename (str): Location of the original PDF. pageSize (str): Either letter or legal. ''' super(PdfEditor, self).__init__() self.pdf = PdfFileReader(filename, strict=strict).getPage(0) self.content = StringIO.StringIO() self.parser = canvas.Canvas( self.content, pagesize=(letter if pageSize == 'letter' else legal)) def drawString(self, x, y, content): '''Args: x (int): X coordinate. y (int): Y coordinate. content (str): String to be written. ''' self.parser.drawString(x, y, content) def setFontSize(self, size): '''Args: size (int): Select size of the font. ''' self.parser.setFontSize(int(size)) def save(self, filename, write_file=True): '''Args: filename (str): Name of the file to be saved. ''' self.parser.save() self.content.seek(0) text = PdfFileReader(self.content) output = PdfFileWriter() self.pdf.mergePage(text.getPage(0)) output.addPage(self.pdf) if write_file: outputStream = open(filename, 'wb') output.write(outputStream) else: outputStream = io.BytesIO() output.write(outputStream) return outputStream
class PdfEditor(object): """Class for modifying a previously existing PDF's. note:: Currently only works 1 page PDF's. Origin is on LOWER left corner. """ def __init__(self, filename, pageSize, strict=True): """Args: filename (str): Location of the original PDF. pageSize (str): Either letter or legal. """ super(PdfEditor, self).__init__() self.pdf = PdfFileReader(filename, strict=strict).getPage(0) self.content = StringIO.StringIO() self.parser = canvas.Canvas(self.content, pagesize=(letter if pageSize == "letter" else legal)) def drawString(self, x, y, content): """Args: x (int): X coordinate. y (int): Y coordinate. content (str): String to be written. """ self.parser.drawString(x, y, content) def setFontSize(self, size): """Args: size (int): Select size of the font. """ self.parser.setFontSize(int(size)) def save(self, filename, write_file=True): """Args: filename (str): Name of the file to be saved. """ self.parser.save() self.content.seek(0) text = PdfFileReader(self.content) output = PdfFileWriter() self.pdf.mergePage(text.getPage(0)) output.addPage(self.pdf) if write_file: outputStream = open(filename, "wb") output.write(outputStream) else: outputStream = io.BytesIO() output.write(outputStream) return outputStream
def _draw_matches(output_pdf, matches): matches = list(matches) if len(matches) > 31: match_positions = bracket_64_positions base_layer_filename = _get_template('64teamsingleseeded.pdf') else: match_positions = bracket_32_positions base_layer_filename = _get_template('32teamsingleseeded.pdf') base_layer = PdfFileReader(base_layer_filename).getPage(0) division = matches[0].division tournament = division.tournament base_layer.mergePage(_draw_title(division, tournament)) for match in matches: base_layer.mergePage(_draw_match(match, match_positions)) output_pdf.addPage(base_layer)
def add_image_to_resume(self, image_path): temp_file_name = tempfile.gettempdir() + "logo.pdf" logo_canvas = canvas.Canvas(temp_file_name) logo_canvas.drawImage(image_path, 15, 15) logo_canvas.save() with open(temp_file_name, "rb") as temp_pdf: layer_pdf = PdfFileReader(temp_pdf) output_file = PdfFileWriter() with open(self.options.resume, "rb") as resume_pdf: input_file = PdfFileReader(resume_pdf) input_file.mergePage(layer_pdf.getPage(0)) output_file.write(input_file)
def assign_grades(source, destination, grade_1, grade_2, grade_3, grade_4, grade_5): pdf = PdfFileWriter() imgTemp = BytesIO() imgDoc = canvas.Canvas(imgTemp, pagesize=A4) imgDoc.drawImage('grade_1.png', 105 + 97 * 0, 555, 23, 5 + grade_to_px(grade_1)) imgDoc.drawImage('grade_2.png', 105 + 97 * 1, 555, 23, 5 + grade_to_px(grade_2)) imgDoc.drawImage('grade_3.png', 105 + 97 * 2, 555, 23, 5 + grade_to_px(grade_3)) imgDoc.drawImage('grade_4.png', 105 + 97 * 3, 555, 23, 5 + grade_to_px(grade_4)) imgDoc.drawImage('grade_5.png', 105 + 97 * 4, 555, 23, 5 + grade_to_px(grade_5)) imgDoc.save() page = PdfFileReader(open(source, 'rb')).getPage(-1) overlay = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0) page.mergePage(overlay) output = PdfFileWriter() output.addPage(page) output.write(open(destination, 'wb'))
def _draw_positions(output_pdf, bracket_size): if bracket_size == 32: match_positions = bracket_32_positions base_layer_filename = _get_template('32teamsingleseeded.pdf') elif bracket_size == 64: match_positions = bracket_64_positions base_layer_filename = _get_template('64teamsingleseeded.pdf') else: raise ArgumentError('bracket_size=%d must be 32 or 64' % (bracket_size)) base_layer = PdfFileReader(base_layer_filename).getPage(0) base_layer.mergePage(_draw_title('Division', 'Tournament')) for position in match_positions.items(): base_layer.mergePage(_draw_position(position)) output_pdf.addPage(base_layer)
def buildPDF(self, data, document_root): data = json.loads(data)[0]['fields'] content = StringIO.StringIO() parser = canvas.Canvas(content, pagesize=letter) self.Transaccion(parser, data['Transaccion']) self.Ano_Fiscal(parser, data['Ano_Fiscal']) self.f1(parser, data['f1']) self.f2(parser, data['f2']) self.f3(parser, data['f3']) self.f5(parser, data['f5']) self.f6(parser, data['f6']) self.f8(parser, data['f8'].split('-')) self.f9(parser, data['f9'].split('-')) self.f10(parser, data['f10']) self.f11(parser, data['f11']) self.f12(parser, data['f12']) self.f13(parser, data['f13']) self.f14(parser, data['f14']) self.f15(parser, data['f15']) self.f16(parser, data['f16']) self.f17(parser, data['f17']) self.f18(parser, data['f18']) self.f19(parser, data['f19']) self.f20(parser, data['f20']) self.f21(parser, data['f21']) self.f22(parser, data['f22']) self.f23(parser, data['f23']) self.f24(parser, data['f24']) self.f25(parser, data['f25']) self.f26(parser, data['f26']) self.f27(parser, data['f27']) self.f30(parser, data['f30']) parser.save() content.seek(0) text = PdfFileReader(content) form = PdfFileReader(document_root + '/t02.pdf').getPage(0) output = PdfFileWriter() form.mergePage(text.getPage(0)) output.addPage(form) outputStream = open(document_root + '/t02-gen.pdf', 'wb') output.write(outputStream) self.form = output
def buildPDF(self, data, document_root): data = json.loads(data)[0]['fields'] content = StringIO.StringIO() parser = canvas.Canvas(content, pagesize=letter) self.Transaccion(parser, data['Transaccion']) self.Ano_Fiscal(parser, data['Ano_Fiscal']) self.f1(parser, data['f1']) self.f2(parser, data['f2']) self.f3(parser, data['f3']) self.f5(parser, data['f5']) self.f6(parser, data['f6']) self.f8(parser, data['f8'].split('-')) self.f9(parser, data['f9'].split('-')) self.f10(parser, data['f10']) self.f11(parser, data['f11']) self.f12(parser, data['f12']) self.f13(parser, data['f13']) self.f14(parser, data['f14']) self.f15(parser, data['f15']) self.f16(parser, data['f16']) self.f17(parser, data['f17']) self.f18(parser, data['f18']) self.f19(parser, data['f19']) self.f20(parser, data['f20']) self.f21(parser, data['f21']) self.f22(parser, data['f22']) self.f23(parser, data['f23']) self.f24(parser, data['f24']) self.f25(parser, data['f25']) self.f26(parser, data['f26']) self.f27(parser, data['f27']) self.f30(parser, data['f30']) parser.save() content.seek(0) text = PdfFileReader(content) form = PdfFileReader(document_root+'/t02.pdf').getPage(0) output = PdfFileWriter() form.mergePage(text.getPage(0)) output.addPage(form) outputStream = open(document_root+'/t02-gen.pdf', 'wb') output.write(outputStream) self.form = output
def merge_pdf_overlay(orig, overlay, outfile=None): """ Makes an overlay using the first pages of the pdfs specified. Takes 2 file like objects, output into either a third or a tempfile """ if outfile is None: outfile = BytesIO() orig = PdfFileReader(orig).getPage(0) overlay = PdfFileReader(overlay).getPage(0) orig.mergePage(overlay) writer = PdfFileWriter() writer.addPage(orig) writer.write(outfile) outfile.flush() return outfile
def merge_pdf_overlay(orig, overlay, outfile=None): """ Makes an overlay using the first pages of the pdfs specified. Takes 2 file like objects, output into either a third or a tempfile """ if outfile is None: outfile = BytesIO() orig = PdfFileReader(orig).getPage(0) overlay = PdfFileReader(overlay).getPage(0) orig.mergePage(overlay) writer = PdfFileWriter() writer.addPage(orig) writer.write(outfile) outfile.flush() return outfile
def _gen_pdf(self): if self.count < 10: num = '0000{}'.format(self.count) elif self.count < 100: num = '000{}'.format(self.count) elif self.count < 1000: num = '00{}'.format(self.count) elif self.count < 10000: num = '0{}'.format(self.count) else: num = '{}'.format(self.count) num = 'WS - {}'.format(num) today = time.strftime('%a %b %d %Y %H:%M:%S') date = 'London, {}'.format(today) imgTemp = BytesIO() imgdoc = canvas.Canvas(imgTemp, pagesize=A5) imgdoc.drawImage(self.image, self.IMG_POS_X, self.IMG_POS_Y, self.IMG_SIZE, self.IMG_SIZE, preserveAspectRatio=True) imgdoc.setFont(self.PS_FONT_NAME, self.FONT_SIZE) imgdoc.drawString(self.NUM_POS_X, self.NUM_POS_Y, num) imgdoc.drawString(self.SCORE_POS_X, self.SCORE_POS_Y, self.score) imgdoc.drawString(self.DATE_POS_X, self.DATE_POS_Y, date) imgdoc.drawString(self.CLASS_POS_X, self.CLASS_POS_Y, self.CLASSES[self.label.lower()]) imgdoc.save() # erase image file from system os.remove(self.image) img_pdf = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0) img_pdf.rotateClockwise(90) base = PdfFileReader(open(self.template, 'rb')).getPage(0) base.rotateClockwise(90) base.mergePage(img_pdf) pdf = PdfFileWriter() pdf.addPage(base) pdf.write(open('{}/{}.pdf'.format(self.destination, self.score), 'wb'))
def add_background_to_pdf( filename_in, filename_out=None, filename_letterhead=None, filename_background=None, new_title="", new_author="", ): """Merges a one page letterhead to an invoice and sets author and title of the doc info for multi page pdfs, its possible to define an extra page """ if not filename_letterhead: return use_tmpfile = False if not filename_out: filename_out = tempfile.NamedTemporaryFile( mode="w+b", delete=False, suffix=".pdf" ).name use_tmpfile = True if not filename_background: filename_background = filename_letterhead with open(filename_in, "rb") as pdf_in, open( filename_background, "rb" ) as pdf_lb, open(filename_letterhead, "rb") as pdf_lh: input_pdf = PdfFileReader(pdf_in) output_pdf = PdfFileWriter() # metadata # noinspection PyProtectedMember infodict = output_pdf._info.getObject() for k, v in input_pdf.documentInfo.items(): infodict.update({NameObject(k): createStringObject(v)}) infodict.update({NameObject("/Title"): createStringObject(new_title)}) infodict.update({NameObject("/Author"): createStringObject(new_author)}) # add first page # get the first invoice page, merge with letterhead letterhead = PdfFileReader(pdf_lh).getPage(0) letterhead.mergePage(input_pdf.getPage(0)) output_pdf.addPage(letterhead) # add other pages for i in range(1, input_pdf.getNumPages()): background = PdfFileReader(pdf_lb).getPage(0) background.mergePage(input_pdf.getPage(i)) output_pdf.addPage(background) # save pdf with open(filename_out, "wb") as pdf_out: output_pdf.write(pdf_out) if use_tmpfile: backup_pdf = "{}.bak".format(filename_in) shutil.move(filename_in, backup_pdf) shutil.move(filename_out, filename_in) os.remove(backup_pdf)
def generate_label(order_id, coffee_id=None): pdfmetrics.registerFont(AMATIC_BOLD) pdfmetrics.registerFont(HOOKCOFFEE_CLUB) order = Order.objects.get(id=order_id) # coffee_id for Discovery Pack: coffee = (CoffeeType.objects.get(id=coffee_id) if coffee_id else order.coffee) package = order.package brew = order.brew.name recipient = order.shipping_address['recipient_name'] name = '{:^35}'.format(recipient) if coffee.roasted_on: roasted_on = coffee.roasted_on else: roasted_on = timezone.now() + timedelta(days=-3) side = 'left' if coffee.label_position == 1 else 'right' roasted_on = datetime.strftime(roasted_on, '%d / %b / %y') ground_on = ('' if package == Preferences.WHOLEBEANS else datetime.strftime(order.shipping_date, '%d / %b / %y')) if not coffee.hasLabel: raise ValueError(coffee.id, coffee) if package == Preferences.DRIP_BAGS: template_src = os.path.join(settings.MEDIA_ROOT, str(coffee.label_drip)) else: template_src = os.path.join(settings.MEDIA_ROOT, str(coffee.label)) buffer = StringIO() c = canvas.Canvas(buffer) c.setLineWidth(.3) c.setFont('Amatic-Bold', 16) x, y = ELEMENT_POSITION['name'][side] c.drawString(x, y, name) c.setFont('Amatic-Bold', 14) x, y = ELEMENT_POSITION['roasted_on'][side] c.drawString(x, y, roasted_on) x, y = ELEMENT_POSITION['ground_on'][side] c.drawString(x, y, ground_on) if package != Preferences.DRIP_BAGS: if package == Preferences.WHOLEBEANS: prefix = '' ground_for = 'Whole beans' elif package == Preferences.GRINDED: prefix = 'ground for' if brew == 'None': prefix = '' ground_for = ' Ground' elif brew == 'Drip': ground_for = 'Dripper' else: ground_for = brew c.setFont('HookCoffeeClub', 8) ground_for_prefix = ELEMENT_POSITION['ground_for'][side] c.drawString(ground_for_prefix[0], ground_for_prefix[1], prefix) c.setFont('HookCoffeeClub', 16) brew_pos = ELEMENT_POSITION['package'][side] c.drawString(brew_pos[0], brew_pos[1], ground_for) barcode_pos = ELEMENT_POSITION['barcode'][side] barcode = _create_qr(order.pk) barcode.drawOn(c, *barcode_pos) c.showPage() c.save() page = PdfFileReader(file(template_src, 'rb')).getPage(0) overlay = PdfFileReader(StringIO(buffer.getvalue())).getPage(0) page.mergePage(overlay) return page
def generate_product_label(order): if order.coffee.roasted_on: roasted_on = order.coffee.roasted_on else: roasted_on = timezone.now() + timedelta(days=-3) package = order.package brew = order.brew.name side = 'left' if order.coffee.label_position == 1 else 'right' roasted_on = datetime.strftime(roasted_on, '%d / %b / %y') ground_on = ('' if package == Preferences.WHOLEBEANS else datetime.strftime(order.shipping_date, '%d / %b / %y')) if package == Preferences.DRIP_BAGS: template_src = os.path.join(settings.MEDIA_ROOT, str(order.coffee.label_drip)) else: template_src = os.path.join(settings.MEDIA_ROOT, str(order.coffee.label)) pdfmetrics.registerFont(AMATIC_BOLD) pdfmetrics.registerFont(DROIDSANSFALLBACK) # pdfmetrics.registerFont(AVENIRNEXT) buffer = BytesIO() c = canvas.Canvas(buffer) c.setLineWidth(.3) recipient = order.shipping_address['recipient_name'] if _is_ascii_str(recipient): recipient = '{:^35}'.format(recipient) font_for_name = 'Amatic-Bold' else: recipient = '{:^15}'.format(recipient) font_for_name = 'DroidSansFallback' c.setFont(font_for_name, 16) x, y = ELEMENT_POSITION['name'][side] c.drawString(x, y, recipient) c.setFont('Amatic-Bold', 14) x, y = ELEMENT_POSITION['roasted_on'][side] c.drawString(x, y, roasted_on) x, y = ELEMENT_POSITION['ground_on'][side] c.drawString(x, y, ground_on) c.setFont('Helvetica', 16) if package == Preferences.GRINDED: brew_pos = ELEMENT_POSITION['package'].get(brew) if brew_pos: brew_pos = brew_pos[side] c.drawString(brew_pos[0], brew_pos[1], '✔') elif package == Preferences.WHOLEBEANS: brew_pos = ELEMENT_POSITION['package']['Wholebeans'][side] c.drawString(brew_pos[0], brew_pos[1], '✔') barcode_pos = ELEMENT_POSITION['barcode'][side] barcode = _create_qr(order.pk) barcode.drawOn(c, *barcode_pos) c.showPage() c.save() page = PdfFileReader(template_src).getPage(0) overlay = PdfFileReader(buffer).getPage(0) page.mergePage(overlay) label = BytesIO() output = PdfFileWriter() output.addPage(page) output.write(label) return label
def create_ilwtest_certificate(self, event, participantname, teststatus): training_start = event.event_start_date training_end = event.event_end_date event_type = event.event_type response = HttpResponse(content_type='application/pdf') filename = (participantname+'-'+teststatus.fossid.foss+"-Participant-Test-Certificate").replace(" ", "-"); response['Content-Disposition'] = 'attachment; filename='+filename+'.pdf' imgTemp = BytesIO () imgDoc = canvas.Canvas(imgTemp) # Title imgDoc.setFont('Helvetica', 25, leading=None) imgDoc.drawCentredString(405, 470, "Certificate for Completion of Training") #password certificate_pass = '' if teststatus.cert_code: certificate_pass = teststatus.cert_code teststatus.part_status = 3 #certificate downloaded test over teststatus.save() else: certificate_pass = str(teststatus.participant_id)+id_generator(10-len(str(teststatus.participant_id))) teststatus.cert_code = certificate_pass teststatus.part_status = 3 #certificate downloaded test over teststatus.save() imgDoc.setFillColorRGB(211, 211, 211) imgDoc.setFont('Helvetica', 10, leading=None) imgDoc.drawString(10, 6, certificate_pass) # Draw image on Canvas and save PDF in buffer imgPath = settings.MEDIA_ROOT +"sign.jpg" imgDoc.drawImage(imgPath, 600, 100, 150, 76) #paragraphe text = "This is to certify that <b>"+participantname +"</b> successfully passed a \ <b>"+teststatus.fossid.foss+"</b> test, remotely conducted by the Spoken Tutorial project, IIT Bombay, under an honour invigilation system.\ <br /> Self learning through Spoken Tutorials and passing an online test completes the training programme." centered = ParagraphStyle(name = 'centered', fontSize = 16, leading = 30, alignment = 0, spaceAfter = 20 ) p = Paragraph(text, centered) p.wrap(650, 200) p.drawOn(imgDoc, 4.2 * cm, 7 * cm) imgDoc.save() # Use PyPDF to merge the image-PDF into the template if event_type == "FDP": page = PdfFileReader(open(settings.MEDIA_ROOT +"fdptr-certificate.pdf","rb")).getPage(0) else: page = PdfFileReader(open(settings.MEDIA_ROOT +"tr-certificate.pdf","rb")).getPage(0) overlay = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0) page.mergePage(overlay) #Save the result output = PdfFileWriter() output.addPage(page) #stream to browser outputStream = response output.write(response) outputStream.close() return response
def create_fdptraining_certificate(self, event, participantname): training_start = event.event_start_date training_end = event.event_end_date event_type = event.event_type response = HttpResponse(content_type='application/pdf') filename = (participantname+'-'+event.foss.foss+"-Participant-Certificate").replace(" ", "-"); response['Content-Disposition'] = 'attachment; filename='+filename+'.pdf' imgTemp = BytesIO () imgDoc = canvas.Canvas(imgTemp) # Title imgDoc.setFont('Helvetica', 35, leading=None) imgDoc.drawCentredString(405, 470, "Certificate of Participation") #password certificate_pass = '' imgDoc.setFillColorRGB(211, 211, 211) imgDoc.setFont('Helvetica', 10, leading=None) imgDoc.drawString(10, 6, certificate_pass) # Draw image on Canvas and save PDF in buffer imgPath = settings.MEDIA_ROOT +"sign.jpg" imgDoc.drawImage(imgPath, 600, 100, 150, 76) #paragraphe text = "This is to certify that <b>"+participantname +"</b> has participated in \ <b>"+event.get_event_type_display()+"</b> from <b>"\ + str(training_start) +"</b> to <b>"+ str(training_end) +\ "</b> on <b>"+event.foss.foss+"</b> organized by <b>"+\ event.host_college.institution_name+\ "</b> with course material provided by Spoken Tutorial Project, IIT Bombay.\ <br /><br /> This training is offered by the Spoken Tutorial Project, IIT Bombay." centered = ParagraphStyle(name = 'centered', fontSize = 16, leading = 30, alignment = 0, spaceAfter = 20 ) p = Paragraph(text, centered) p.wrap(650, 200) p.drawOn(imgDoc, 4.2 * cm, 7 * cm) imgDoc.save() # Use PyPDF to merge the image-PDF into the template if event_type == "FDP": page = PdfFileReader(open(settings.MEDIA_ROOT +"fdptr-certificate.pdf","rb")).getPage(0) else: page = PdfFileReader(open(settings.MEDIA_ROOT +"tr-certificate.pdf","rb")).getPage(0) overlay = PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0) page.mergePage(overlay) #Save the result output = PdfFileWriter() output.addPage(page) #stream to browser outputStream = response output.write(response) outputStream.close() return response
def stripe_send_friend(request): context = { 'success': False, } token = request.POST['stripeToken'] recipient = request.POST.get('recipient_name') sender_email = request.POST.get('email') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') credits_amount = request.POST.get('post_credits') voucher_code = ReferralVoucher.get_random_code(size=8) try: charge = stripe.Charge.create( amount=int(credits_amount) * 100, currency='SGD', source=token, description='Gift voucher from {} to {}'.format( sender_email, recipient)) except Exception as e: raise e else: GiftVoucher.objects.create(sender_email=sender_email, sender_fname=first_name, sender_lname=last_name, recipient=recipient, amount=credits_amount, code=voucher_code) # Create a voucher pdf static_path = settings.STATIC_PATH media_root = settings.MEDIA_ROOT response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=voucher.pdf' font_src = os.path.join(static_path, 'fonts/amatic/Amatic-Bold.ttf') pdfmetrics.registerFont(TTFont('Amatic-Bold', font_src)) font_src = os.path.join(static_path, 'fonts/brusher/Brusher-Regular.ttf') pdfmetrics.registerFont(TTFont('Brusher-Regular', font_src)) buffer = StringIO() buffer2 = StringIO() outfilename = 'voucher_{}.pdf'.format(sender_email) outfiledir = os.path.join(media_root, 'gift_vouchers') outfilepath = os.path.join(outfiledir, outfilename) if not os.path.exists(outfiledir): os.makedirs(outfiledir) c = canvas.Canvas(buffer) c2 = canvas.Canvas(buffer2) # c.setLineWidth(.3) c.setFont('Amatic-Bold', 60) c.drawString(365, 157, '$' + credits_amount) c2.setFont('Amatic-Bold', 24) c2.drawString(150, 288, voucher_code) f_recipient = '{:^12}'.format(recipient) if len(recipient) < 9: c.setFont('Brusher-Regular', 35) c.drawString(75, 250, f_recipient) else: c.setFont('Brusher-Regular', 28) c.drawString(65, 250, f_recipient) c.showPage() c2.showPage() c.save() c2.save() template_src = os.path.join(static_path, 'vouchers/gift_voucher.pdf') page = PdfFileReader(file(template_src, "rb")).getPage(0) page2 = PdfFileReader(file(template_src, "rb")).getPage(1) overlay = PdfFileReader(StringIO(buffer.getvalue())).getPage(0) overlay2 = PdfFileReader(StringIO(buffer2.getvalue())).getPage(0) page.mergePage(overlay) page2.mergePage(overlay2) output = PdfFileWriter() output.addPage(page) output.addPage(page2) output.write(open(outfilepath, 'wb')) # Send notification send_email_async.delay( subject='A Lovely Gift Voucher Within', template='Gift Vouchers (done)', to_email=sender_email, merge_vars={ 'SENDER': first_name, 'RECEPIENT': recipient, 'AMOUNT': credits_amount, 'DOMAIN_NAME': request.META.get('HTTP_HOST'), }, attachments=[(outfilename, outfilepath, 'application/pdf')], ) context = { 'success': True, } return context