def create_first_page(): TOP = (29.7 - 5) * cm LEFT = 4 * cm RIGHT = (21 - 4) * cm FONT_SIZE = 10 FONT = "Plex" text = "PyJournal year 2020" image_path = "logo.png" # text right font = FONT font_size = FONT_SIZE canvas = Canvas("first_page.pdf", pagesize=A4) canvas.setFont(font, font_size) canvas.setFillColor(black) text_width = pdfmetrics.stringWidth(text, font, font_size) text_height = int(FONT_SIZE * 1.2) # TODO not correct canvas.drawString(RIGHT - text_width, TOP - text_height, text) # logo img = utils.ImageReader(image_path) img_width, img_height = img.getSize() aspect = img_height / float(img_width) display_width = 100 display_height = (display_width * aspect) canvas.drawImage(image_path, LEFT, TOP - display_height, width=display_width, height=display_height, mask="auto") canvas.save()
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): """Makes a one-page PDF with just the drawing. If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.""" d = renderScaledDrawing(d) c = Canvas(fn) if msg: c.setFont(rl_config.defaultGraphicsFontName, 36) c.drawString(80, 750, msg) c.setTitle(msg) if autoSize: c.setPageSize((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) else: #show with a title c.setFont(rl_config.defaultGraphicsFontName, 12) y = 740 i = 1 y = y - d.height draw(d, c, 80, y, showBoundary=showBoundary) c.showPage() c.save() if sys.platform=='mac' and not hasattr(fn, "write"): try: import macfs, macostools macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") macostools.touched(fn) except: pass
def test_06_fontsize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import red, magenta c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont("Times-Roman", 20) c.setFillColor(red) c.saveState() c.drawCentredString(2.75*inch, 2.5*inch,"Font size excmples") c.setFillColor(magenta) size = 7 x = 2.3 * inch y = 1.3 * inch for line in range(7): c.setFont("Helvetica", size) c.drawRightString(x, y, "%s points" % size) c.drawString(x,y, "test") y = y-size*1.2 size = size+1.5 c.restoreState() c.drawString(0,0, "%s" % c.getAvailableFonts()) c.showPage() c.save()
def generate_pdf(request, id_): paciente = Paciente.objects.get(id=id_) nombre = "Patient-" + paciente.nombre_y_apellido.replace(" ", "_") + ".pdf" c = Canvas(nombre) p = PdfPrinter(c, 60, 120) c.setTitle("Patient information") p.create_header("Patient " + paciente.nombre_y_apellido) p.horizontal_line() p.create_text_line("DNI", paciente.dni) p.create_text_line("Email", paciente.mail) p.create_text_line("Residence", paciente.domicilio) p.create_text_line("Phone number", paciente.telefono) p.create_text_line("Date of birth", paciente.fecha_nacimiento) if paciente.obra_social: p.create_text_line("Healthcare", paciente.obra_social) p.create_text_line("Personal history", paciente.antecedentes_personales + " ") if paciente.obito: p.create_text_line("Passed away", "Yes") p.horizontal_line() c.setFont("Helvetica-Bold", 16) c.drawString(350, 723, 'Contact information') p.create_contact_line("First name", paciente.nombre_contacto) p.create_contact_line("Last name", paciente.apellido_contacto) p.create_contact_line("Phone number", paciente.telefono) p.create_contact_line("Kinship", paciente.parentesco_contacto) p.create_half_title("Hospitalizations") for hospitalization in paciente.internacion_set.all(): p.create_hospitalization(hospitalization) c.showPage() c.save() return FileResponse(open(nombre, 'rb'), content_type='application/pdf')
def testUtf8FileName(self): fn = outputfile('test_pdfbase_utf8_filename') if not isUnicode(fn): fn = fn.decode('utf8') fn += u'_portr\xe4t.pdf' c = Canvas(fn) c.drawString(100, 700, u'Filename=' + fn) c.save()
def web_report_to_PDF(projects, developers, date_from, date_to): projects_data = {} branches_data = {} developers_data = {} developers_branch_data = {} developers_project_data = {} headtext = "Red Hat GITVIEW team report" timetext =\ date_from.strftime("%Y.%m.%d") + '_' + date_to.strftime("%Y.%m.%d") filename = '_'.join([timetext, 'gitview.pdf']) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] =\ 'attachment; filename=%s' % filename can = Canvas(response) can.setFont("Helvetica-Bold", 17.5) can.drawString(2.2*inch, 9*inch, "GIT VIEW TEAM DATA REPORT") can.setFont("Helvetica", 10.5) can.drawString(3.2*inch, 8.5*inch, timetext) [projects_data, developers_data, branches_data, developers_project_data, developers_branch_data] = \ team_report_data(projects, developers, date_from, date_to) pdf_report(projects_data, developers_data, branches_data, developers_project_data, developers_branch_data, can, headtext) return response
def gerar_pdf(dados): byte_array = io.BytesIO() if not dados or len(dados) < 1: c = Canvas(byte_array) c.drawString(100,750,"Sem registros") c.save() else: rpt = Report(dados) rpt.detailband = Band([ Element((36, 0), ("Helvetica", 11), key = "nome", align='left'), Element((236, 0), ("Helvetica", 11), key = "email"), Element((380, 0), ("Helvetica", 11), key = "data_nascimento"), Element((500, 0), ("Helvetica", 11), key = "cpf"), ]) rpt.pageheader = Band([ Element((36, 0), ("Times-Bold", 20), text = "Usuários"), Element((36, 24), ("Helvetica", 12), text = "Nome", align='left'), Element((236, 24), ("Helvetica", 12), text = "E-mail"), Element((380, 24), ("Helvetica", 12), text = "Data Nascimento"), Element((500, 24), ("Helvetica", 12), text = "CPF"), Rule((36, 42), 7.5*72, thickness = 2), ]) rpt.pagefooter = Band([ Rule((36, 42), 7.5*72, thickness = 2), Element((36, 16), ("Helvetica-Bold", 12), sysvar = "pagenumber", format = lambda x: "Página %d" % x), ]) c = Canvas(byte_array, (72*11, 72*8.5)) rpt.generate(c) c.save() byte_array.seek(io.SEEK_SET) return byte_array '''
def get_pdf(self, text, use_design=False): """ Given the text, produces an A4 blank PDF with the text put in the position given by the tranlsation box. :param text: Text to put inside a translation box :param use_design: Set to true to use a design in the background :return: Rendered PDF :rtype: pypdf.PdfFileReader if use_design is False or PdfFileWriter """ self.ensure_one() packet = StringIO.StringIO() can = Canvas(packet, bottomup=0) text_wrap = self._wrap_text(text, can._fontname, can._fontsize) top = self.top * inch left = self.left * inch for line in text_wrap[:self.nb_lines + 1]: can.drawString(left, top, line) top += can._leading can.save() # Move to the beginning of the StringIO buffer packet.seek(0) remaining = '' if len(text_wrap) > self.nb_lines: remaining = ' '.join(text_wrap[self.nb_lines + 1:]) out_pdf = PdfFileReader(packet) if use_design: design_pdf_path = self.env['ir.config_parameter'].get_param( 'sbc_compassion.composition_design') if design_pdf_path: design_pdf = PdfFileReader(file(design_pdf_path, 'rb')) page = design_pdf.getPage(0) page.mergePage(out_pdf.getPage(0)) out_pdf = PdfFileWriter() out_pdf.addPage(page) return out_pdf, remaining
def test_06_fontsize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import red, magenta c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont("Times-Roman", 20) c.setFillColor(red) c.saveState() c.drawCentredString(2.75 * inch, 2.5 * inch, "Font size excmples") c.setFillColor(magenta) size = 7 x = 2.3 * inch y = 1.3 * inch for line in range(7): c.setFont("Helvetica", size) c.drawRightString(x, y, "%s points" % size) c.drawString(x, y, "test") y = y - size * 1.2 size = size + 1.5 c.restoreState() c.drawString(0, 0, "%s" % c.getAvailableFonts()) c.showPage() c.save()
def get_chart(self, chart, fmt, data, width=1000, params=None): chart = BytesIO() canvas = Canvas(chart, pagesize=(140, 140)) canvas.drawString(10, 70, "This is a diagram") canvas.save() chart.seek(0) return chart
def draw_text_on_annotation(pdf: canvas.Canvas, annotation: pdfrw.PdfDict, text: str) -> None: # canvas drawing modified from https://medium.com/@zwinny/filling-pdf-forms-in-python-the-right-way-eb9592e03dba sides_positions = annotation.Rect left = min(float(sides_positions[0]), float(sides_positions[2])) bottom = min(float(sides_positions[1]), float(sides_positions[3])) pdf.drawString(x=left + PADDING, y=bottom + PADDING, text=str(text))
def test(): # only works if you have cirrect encodings on your box! c = Canvas('test_japanese.pdf') c.setFont('Helvetica', 30) c.drawString(100, 700, 'Japanese Font Support') pdfmetrics.registerFont(CIDFont('HeiseiMin-W3', '90ms-RKSJ-H')) pdfmetrics.registerFont(CIDFont('HeiseiKakuGo-W5', '90ms-RKSJ-H')) # the two typefaces c.setFont('HeiseiMin-W3-90ms-RKSJ-H', 16) # this says "This is HeiseiMincho" in shift-JIS. Not all our readers # have a Japanese PC, so I escaped it. On a Japanese-capable # system, print the string to see Kanji message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B' c.drawString(100, 675, message1) c.save() print('saved test_japanese.pdf') ## print 'CMAP_DIR = ', CMAP_DIR ## tf1 = CIDTypeFace('HeiseiMin-W3') ## print 'ascent = ',tf1.ascent ## print 'descent = ',tf1.descent ## for cid in [1,2,3,4,5,18,19,28,231,1742]: ## print 'width of cid %d = %d' % (cid, tf1.getCharWidth(cid)) encName = '90ms-RKSJ-H' enc = CIDEncoding(encName) print(message1, '->', enc.translate(message1)) f = CIDFont('HeiseiMin-W3', '90ms-RKSJ-H') print('width = %0.2f' % f.stringWidth(message1, 10))
def test0(self): "A basic document drawing some strings" self.luxi = TTFont("DejaVu", "DejaVuSans.ttf") pdfmetrics.registerFont(self.luxi) # if they do not have the Japanese font files, go away quietly #from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile ## enc = 'ETenms-B5-H' ## try: ## findCMapFile(enc) ## except: ## #they don't have the font pack, return silently ## print 'CMap not found' ## return #pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light')) c = Canvas(outputfile('test_multibyte_gr.pdf')) c.setFont('Helvetica', 24) c.drawString(100,700, 'Greek characters Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: ') hBoxText('Αυτό είναι ενα δοκιμαστικό κείμενο.' , c, 100, 600, 'DejaVu') ## c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_gr.pdf')
def testUtf8FileName(self): fn=outputfile('test_pdfbase_utf8_filename') if not isUnicode(fn): fn = fn.decode('utf8') fn += u'_portr\xe4t.pdf' c = Canvas(fn) c.drawString(100,700, u'Filename='+fn) c.save()
def ___test2_all(self): """Dumps out ALl GLYPHS in a CID font. Reach for your microscope :-)""" try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('90ms-RKSJ-H') findCMapFile('Identity-H') except: #don't have the font pack. return silently return pdfmetrics.registerFont(CIDFont('HeiseiMin-W3', 'Identity-H')) c = Canvas('test_japanese_2.pdf') c.setFont('Helvetica', 30) c.drawString(100, 800, 'All Glyphs in Adobe-Japan-1-2 collection!') # the two typefaces c.setFont('HeiseiMin-W3-Identity-H', 2) x0 = 50 y0 = 700 dx = 2 dy = 2 for row in range(256): for cell in range(256): s = chr(row) + chr(cell) x = x0 + cell * dx y = y0 - row * dy c.drawString(x, y, s) c.save() if VERBOSE: print 'saved ' + outputfile('test_multibyte_jpn.pdf')
def test(): # only works if you have cirrect encodings on your box! c = Canvas('test_japanese.pdf') c.setFont('Helvetica', 30) c.drawString(100,700, 'Japanese Font Support') pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-H')) pdfmetrics.registerFont(CIDFont('HeiseiKakuGo-W5','90ms-RKSJ-H')) # the two typefaces c.setFont('HeiseiMin-W3-90ms-RKSJ-H', 16) # this says "This is HeiseiMincho" in shift-JIS. Not all our readers # have a Japanese PC, so I escaped it. On a Japanese-capable # system, print the string to see Kanji message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B' c.drawString(100, 675, message1) c.save() print 'saved test_japanese.pdf' ## print 'CMAP_DIR = ', CMAP_DIR ## tf1 = CIDTypeFace('HeiseiMin-W3') ## print 'ascent = ',tf1.ascent ## print 'descent = ',tf1.descent ## for cid in [1,2,3,4,5,18,19,28,231,1742]: ## print 'width of cid %d = %d' % (cid, tf1.getCharWidth(cid)) encName = '90ms-RKSJ-H' enc = CIDEncoding(encName) print message1, '->', enc.translate(message1) f = CIDFont('HeiseiMin-W3','90ms-RKSJ-H') print 'width = %0.2f' % f.stringWidth(message1, 10)
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): """Makes a one-page PDF with just the drawing. If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.""" d = renderScaledDrawing(d) c = Canvas(fn) if msg: c.setFont(rl_config.defaultGraphicsFontName, 36) c.drawString(80, 750, msg) c.setTitle(msg) if autoSize: c.setPageSize((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) else: #show with a title c.setFont(rl_config.defaultGraphicsFontName, 12) y = 740 i = 1 y = y - d.height draw(d, c, 80, y, showBoundary=showBoundary) c.showPage() c.save() if sys.platform == 'mac' and not hasattr(fn, "write"): try: import macfs, macostools macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") macostools.touched(fn) except: pass
def draw_label(self, c: Canvas, col: int, row: int, redemption_code: str): x = self.left_margin + ( col + 0.5) * self.label_width + col * self.inner_margin y = self.page_height - self.top_margin - (row + 0.5) * self.label_height # Drawing label bounds helps when adjusting layout. Not for production. # self.draw_label_bounds(c, x, y) c.setFont("Courier-Bold", 13) c.drawString(x - 80, y + 14, redemption_code) c.setFont("Helvetica", 10) # Space to enter redemption month and day. p = c.beginPath() p.moveTo(x + 20, y + 12) p.lineTo(x + 45, y + 12) p.moveTo(x + 55, y + 12) p.lineTo(x + 80, y + 12) p.close() c.drawPath(p) c.drawCentredString(x + 15, y + 16, 'm:') c.drawCentredString(x + 50, y + 16, 'd:') # Space to enter redeemer's email address. p = c.beginPath() p.moveTo(x - 80, y - 14) p.lineTo(x + 80, y - 14) p.close() c.drawPath(p) c.drawCentredString(x, y - 24, 'email address')
def writePDF(drawings): "Create and save a PDF file containing some drawings." pdfPath = os.path.splitext(sys.argv[0])[0] + '.pdf' c = Canvas(pdfPath) c.setFont(_FONTS[0], 32) c.drawString(80, 750, 'ReportLab Graphics-Shapes Test') # Print drawings in a loop, with their doc strings. c.setFont(_FONTS[0], 12) y = 740 i = 1 for (drawing, docstring, funcname) in drawings: if y < 300: # Allows 5-6 lines of text. c.showPage() y = 740 # Draw a title. y = y - 30 c.setFont(_FONTS[2],12) c.drawString(80, y, '%s (#%d)' % (funcname, i)) c.setFont(_FONTS[0],12) y = y - 14 textObj = c.beginText(80, y) textObj.textLines(docstring) c.drawText(textObj) y = textObj.getY() y = y - drawing.height drawing.drawOn(c, 80, y) i = i + 1 c.save() print 'wrote %s ' % pdfPath
def ___test2_all(self): """Dumps out ALl GLYPHS in a CID font. Reach for your microscope :-)""" try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('90ms-RKSJ-H') findCMapFile('Identity-H') except: #don't have the font pack. return silently return pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','Identity-H')) c = Canvas('test_japanese_2.pdf') c.setFont('Helvetica', 30) c.drawString(100,800, 'All Glyphs in Adobe-Japan-1-2 collection!') # the two typefaces c.setFont('HeiseiMin-W3-Identity-H', 2) x0 = 50 y0 = 700 dx = 2 dy = 2 for row in range(256): for cell in range(256): s = chr(row) + chr(cell) x = x0 + cell*dx y = y0 - row*dy c.drawString(x,y,s) c.save() if VERBOSE: print('saved '+outputfile('test_multibyte_jpn.pdf'))
def writePDF(drawings): "Create and save a PDF file containing some drawings." pdfPath = os.path.splitext(sys.argv[0])[0] + '.pdf' c = Canvas(pdfPath) c.setFont(_FONTS[0], 32) c.drawString(80, 750, 'ReportLab Graphics-Shapes Test') # Print drawings in a loop, with their doc strings. c.setFont(_FONTS[0], 12) y = 740 i = 1 for (drawing, docstring, funcname) in drawings: if y < 300: # Allows 5-6 lines of text. c.showPage() y = 740 # Draw a title. y = y - 30 c.setFont(_FONTS[2], 12) c.drawString(80, y, '%s (#%d)' % (funcname, i)) c.setFont(_FONTS[0], 12) y = y - 14 textObj = c.beginText(80, y) textObj.textLines(docstring) c.drawText(textObj) y = textObj.getY() y = y - drawing.height drawing.drawOn(c, 80, y) i = i + 1 c.save() print 'wrote %s ' % pdfPath
def clear(self): num_tasks_completed = int(''.join( i for i in self.ui.completeLabel.text() if i.isdigit())) num_tasks_incompleted = int(''.join( i for i in self.ui.incompleteLabel.text() if i.isdigit())) time_worked = self.ui.timeWorkedLabel.text() time_needed_to_finish = self.ui.timeNeededLabel.text() yesterday = date.today() - timedelta(days=1) yesterday = yesterday.strftime("%d-%m-%Y") save_name = os.path.join(os.path.expanduser("~"), "Documents\ToDo+", "Work Report (" + yesterday + ").pdf") report = Canvas(save_name) report.drawString(72, 720, "ToDo+ Work Report (" + yesterday + ")") report.drawString( 72, 690, "Total Number of Tasks: " + str(num_tasks_completed + num_tasks_incompleted)) report.drawString( 72, 670, "Number of Tasks Finished: " + str(num_tasks_completed)) report.drawString( 72, 650, "Number of Tasks Unfinished: " + str(num_tasks_incompleted)) report.drawString( 72, 625, "Task Productivity Score : " + str( round((num_tasks_completed - num_tasks_incompleted) / (num_tasks_completed + num_tasks_incompleted), 2))) report.save() self.tasks = [] self.saveTasks() self.loadTasks()
def test(): c = Canvas('codecharts.pdf') c.setFont('Helvetica-Bold', 24) c.drawString(72, 750, 'Testing code page charts') cc1 = SingleByteEncodingChart() cc1.drawOn(c, 72, 500) cc2 = SingleByteEncodingChart(charsPerRow=32) cc2.drawOn(c, 72, 300) cc3 = SingleByteEncodingChart(charsPerRow=25, hex=0) cc3.drawOn(c, 72, 100) ## c.showPage() ## ## c.setFont('Helvetica-Bold', 24) ## c.drawString(72, 750, 'Multi-byte Kuten code chart examples') ## KutenRowCodeChart(1, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 600) ## KutenRowCodeChart(16, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 450) ## KutenRowCodeChart(84, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 300) ## ## c.showPage() ## c.setFont('Helvetica-Bold', 24) ## c.drawString(72, 750, 'Big5 Code Chart Examples') ## #Big5CodeChart(0xA1, 'MSungStd-Light-Acro','ETenms-B5-H').drawOn(c, 72, 500) c.save() print('saved codecharts.pdf')
def pdf_demo_4(filename, text): # prepare for drawing c = Canvas(filename, pagesize=A4) # do the drawing c.drawString(100, 300, text) # save the pdf file c.save()
def render_side_strip(p: canvas.Canvas, r: GroupReservation): p.setFont("Helvetica", 9) p.rotate(90) p.drawString( 34, -25, "Reservation #" + str(r.id) + ' - Created at: ' + str(r.timestamp) + ' - Pickup date: ' + str(r.pickupDate)) p.rotate(270)
def run(rfc_list= ["1111","22222"], pdf_file="barcode.pdf"): try: os.remove(pdf_file) except: pass c = Canvas(pdf_file) c.setFontSize(size="7") print " %s pag para %s rfcs " % (round(len(rfc_list)/114.0,0), len(rfc_list)) for times in range(0,int(round(len(rfc_list)/114.0,0))): for i in range(0,6): for j in range(1,20): st = code128.Code128() if len(rfc_list) >0 : rfc = rfc_list.pop() else: c.save() sys.exit() st.value = rfc pos_x = i*30*mm pos_y = j*15*mm #print pos_x/mm,pos_y/mm st.drawOn(c, x = pos_x, y = pos_y) c.drawString(pos_x+10*mm, pos_y+7*mm , rfc ) c.showPage() c.setFontSize(size="7") try: f = open(pdf_file, "wb") except IOError: easygui.msgbox("El archivo pdf esta abierto, por lo que no se puede guardar", "Error") sys.exit(0) c.save()
def include_footer(input_file_path, output_file_path, link=None): # Get pages reader = PdfReader(input_file_path) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file_path) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = f"This report is reproducible with FAIR data. Find the source datasets here: {link}" x = 80 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.line(66, 40, page.BBox[2] - 66, 40) canvas.setFont('Helvetica', 8) canvas.drawString(66, 25, footer_text) canvas.linkURL(link, (66, 25, page.BBox[2] - 66, 40)) canvas.restoreState() canvas.showPage() canvas.save()
def ccPDFmake(frontFile, backFile, saveFile, text): canvas = Canvas(saveFile) front = utils.ImageReader(frontFile) back = utils.ImageReader(backFile) canvas.drawImage(front, FRONT_X, FRONT_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') canvas.drawImage(back, BACK_X, BACK_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') if text != "": canvas.saveState() canvas.rotate(55) canvas.setFillColorRGB(.6, .6, .6) canvas.setFont("Times-Roman", 30) canvas.drawString(10 * CM, 0.2 * CM, text) canvas.restoreState() canvas.save() return True
def get_pdf(self, text, use_design=False): """ Given the text, produces an A4 blank PDF with the text put in the position given by the tranlsation box. :param text: Text to put inside a translation box :param use_design: Set to true to use a design in the background :return: Rendered PDF :rtype: pypdf.PdfFileReader if use_design is False or PdfFileWriter """ self.ensure_one() packet = StringIO.StringIO() can = Canvas(packet, bottomup=0) text_wrap = self._wrap_text(text, can._fontname, can._fontsize) top = self.top*inch left = self.left*inch for line in text_wrap[:self.nb_lines+1]: can.drawString(left, top, line) top += can._leading can.save() # Move to the beginning of the StringIO buffer packet.seek(0) remaining = '' if len(text_wrap) > self.nb_lines: remaining = ' '.join(text_wrap[self.nb_lines+1:]) out_pdf = PdfFileReader(packet) if use_design: design_pdf_path = self.env['ir.config_parameter'].get_param( 'sbc_compassion.composition_design') if design_pdf_path: design_pdf = PdfFileReader(file(design_pdf_path, 'rb')) page = design_pdf.getPage(0) page.mergePage(out_pdf.getPage(0)) out_pdf = PdfFileWriter() out_pdf.addPage(page) return out_pdf, remaining
def test(): c = Canvas('codecharts.pdf') c.setFont('Helvetica-Bold', 24) c.drawString(72, 750, 'Testing code page charts') cc1 = SingleByteEncodingChart() cc1.drawOn(c, 72, 500) cc2 = SingleByteEncodingChart(charsPerRow=32) cc2.drawOn(c, 72, 300) cc3 = SingleByteEncodingChart(charsPerRow=25, hex=0) cc3.drawOn(c, 72, 100) ## c.showPage() ## ## c.setFont('Helvetica-Bold', 24) ## c.drawString(72, 750, 'Multi-byte Kuten code chart examples') ## KutenRowCodeChart(1, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 600) ## KutenRowCodeChart(16, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 450) ## KutenRowCodeChart(84, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, 300) ## ## c.showPage() ## c.setFont('Helvetica-Bold', 24) ## c.drawString(72, 750, 'Big5 Code Chart Examples') ## #Big5CodeChart(0xA1, 'MSungStd-Light-Acro','ETenms-B5-H').drawOn(c, 72, 500) c.save() print 'saved codecharts.pdf'
def edit_pdf(filePath): input_file = filePath output_file = filePath # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw header header_text = "Jhon institute" x = 180 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.drawImage('input_logo.jpg', height=60, width=110,x=60, y=700) canvas.setFont('Times-Roman', 14) canvas.drawString(page.BBox[2] -x, 730, header_text) # Draw footer footer_text = "It’s easy to play any musical instrument: all you have to do is touch the right key at " \ "the right time and the instrument will play itself." x = 70 canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.setFont('Times-Roman', 10) canvas.drawString(page.BBox[1] +x, 30, footer_text) canvas.restoreState() canvas.showPage() canvas.save()
def cria_pagina_pesquisa(modelador_paginas: Canvas, pesquisa: Pesquisa, numero_da_pesquisa: int): adiciona_cabecalho_pdf(modelador_paginas) modelador_paginas.setFont('Helvetica', 30) modelador_paginas.drawString(x=7.5 * cm, y=22 * cm, text='Pesquisa ' + str(numero_da_pesquisa)) modelador_paginas.setFont('Helvetica', 20) modelador_paginas.drawString(x=2 * cm, y=20 * cm, text='Título: ' + pesquisa.titulo) modelador_paginas.drawString(x=2 * cm, y=18 * cm, text='Código: ' + str(pesquisa.id)) modelador_paginas.drawString(x=2 * cm, y=16 * cm, text='Tipo de Pesquisa: ' + pesquisa.tipo_de_pesquisa) modelador_paginas.drawString(x=2 * cm, y=14 * cm, text='Investigador Principal: ' + pesquisa.investigador.nome) # aux = 0 # # for dado in pega_dados_monetarios_da_pesquisa(pesquisa.id): # modelador_paginas.drawString(x=2 * cm, y=(12 - aux) * cm, text='dado') # aux += 2 modelador_paginas.showPage()
def to_pdf(filename): target_file = filename.split('.')[0] + '.pdf' target = os.path.join(CP, target_file) source_file = os.path.join(CP, filename) canvas = Canvas(target, pagesize=A4) canvas.translate(0, 0) canvas.setFillColor(blue) font_size = 16 canvas.setFont("Courier", font_size) with open(source_file, 'r') as rh: n = 1 for r in rh: r = r.replace('\t', ' ' * 3) if r == '\n': canvas.drawString(5, A4[1] - n * 20, '') else: canvas.drawString(5, A4[1] - n * 20, r) if n % 60 == 0: canvas.showPage() canvas.setFillColor(blue) canvas.setFont("Courier", font_size) n = 1 n += 1 canvas.save()
def test11_untitled(self): """Test ability to omit document title""" canvas = Canvas('') canvas.drawString(100, 750, "Hello world!") document = canvas.getpdfdata() self.printer_default.spool(document) self.assertPrintedLpr()
def test0(self): "A basic document drawing some strings" self.luxi = TTFont("DejaVu", "DejaVuSans.ttf") pdfmetrics.registerFont(self.luxi) # if they do not have the Japanese font files, go away quietly # from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile ## enc = 'ETenms-B5-H' ## try: ## findCMapFile(enc) ## except: ## #they don't have the font pack, return silently ## print 'CMap not found' ## return # pdfmetrics.registerFont(UnicodeCIDFont('MSung-Light')) c = Canvas(outputfile("test_multibyte_gr.pdf")) c.setFont("Helvetica", 24) c.drawString(100, 700, "Greek characters Font Support") c.setFont("Helvetica", 10) c.drawString(100, 680, "Short sample: ") hBoxText("Αυτό είναι ενα δοκιμαστικό κείμενο.", c, 100, 600, "DejaVu") ## c.save() if VERBOSE: print "saved " + outputfile("test_multibyte_gr.pdf")
def csv_to_pdf(csv_file_path: str): print(f'csv_to_pdf: {csv_file_path}') deck_name = path.basename(csv_file_path)[:-4] canvas = Canvas(f'{deck_name}.pdf', pagesize=landscape(A7)) # 74 x 105 mm with open(csv_file_path) as csv_file: reader = csv.reader(csv_file, delimiter='\t') for row in reader: back = row[0] front = row[1] p_back = Paragraph(back, styles["Title"]) p_back.wrap(width, height) p_back.drawOn(canvas, 0, height/2) canvas.drawString(margin, margin, deck_name) canvas.showPage() p_front = Paragraph(front, styles["Title"]) p_front.wrap(width, height) p_front.drawOn(canvas, 0, height/2) canvas.drawString(margin, margin, deck_name) canvas.showPage() canvas.save()
class pdf: def __init__(self, name, logo): self.text = None self.name = name self.canvas = Canvas(self.name + ".pdf") self.logo = logo from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('times', 'times.ttf')) pdfmetrics.registerFont(TTFont('timesb', 'timesbd.ttf')) if self.logo == "logo.png": self.canvas.drawImage(self.logo, 50, 700, mask="auto") def write_string(self, txt, x, y, font, size): self.canvas.setFont(font, size) self.canvas.drawString(x, y, txt) def write_text(self, txt, x, y, font, size): self.canvas.setFont(font, size) self.text = self.canvas.beginText(x, y) self.text.setFont(font, size) self.text.textLines(txt) self.canvas.drawText(self.text) def save(self): self.canvas.save()
def hello(c: canvas.Canvas = None): c = canvas.Canvas("hello.pdf") from reportlab.lib.units import inch c.translate(inch, inch) c.setFont("Helvetica", 20) c.setStrokeColorRGB(0.2, 0.5, 0.3) c.setFillColorRGB(1, 0, 1) c.line(0, 0, 0, 1.7 * inch) c.line(0, 0, 1 * inch, 0) c.rotate(30) c.rect(0.2 * inch, 0.2 * inch, inch, 1.5 * inch, fill=1) c.rotate(-30) c.setFillColorRGB(0, 0.15, 0.03) c.setFillColorRGB(0.31, 0.15, 0.64) c.drawString( 20, 20, "Hello World from Reportlab" + " TEST LONG STRING WHICH IS REALLY REALLY REALLY REALLY REALLY REALLY REALLY LONG" ) c.showPage() c.save()
def add_footer(input_file, output_file): logging.info("add_footer started") # Get pages reader = PdfReader("%s.pdf" % (input_file)) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas("%s.pdf" % (output_file)) pdfmetrics.registerFont( TTFont('SourceSansPro', 'SourceSansPro-Regular.ttf')) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = "www.borderviolence.eu" x = 80 canvas.saveState() canvas.setStrokeColorRGB(0.19, 0.19, 0.19) canvas.setLineWidth(0.3) canvas.line(75, 78, page.BBox[2] - 66, 78) canvas.setFont('SourceSansPro', 10) canvas.setFillColor(HexColor(0x333333)) canvas.drawString(page.BBox[2] - x, 85, str(page_num)) canvas.drawString(page.BBox[2] - x - 436, 85, footer_text) canvas.restoreState() canvas.showPage() canvas.save() logging.info("PDF with footer %s.pdf was saved" % (output_file)) return 1
def test(self): c = Canvas(outputfile('test_hello.pdf')) c.setAuthor( '\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88' ) c.setFont('Helvetica-Bold', 36) c.drawString(100, 700, 'Hello World') c.save()
def mkPdf(self, id, path): url = "https://cosc426restapi.herokuapp.com/api/Student/" url = url + str(id) response = requests.get(url, headers={'auth-token': token}) data = [] canvas = Canvas(path, pagesize=(612.0, 792.0)) try: curs = response.json() major = '' multiMaj = 0 data.append(curs.get('name')) data.append(curs.get('s_id')) try: data.append('major(s): ' + (curs.get('major'))) data.append(curs.get('s_id') + ' school') except (TypeError, KeyError): data.append("Double major") multiMaj = 1 try: data.append('minor(s): ' + curs.get('minor')) except TypeError: data.append("Double minor") data.append(curs.get('status')) data.append(curs.get('year')) data.append('current credits: ' + str(curs.get('credits'))) data.append(curs.get('sem_id')) data.append('Registering for ' + curs.get('registering_for') + ' semester') data.append(curs.get('enrll')) data.append(curs.get('advisor_mail')) major = (curs.get('major')) data.append("-----------------------------------------") data.append("Current courses:") #obj = stud.find_one({'s_id': id}) for x in curs['taking_course']: data.append(" " + x.get('subject') + " " + str(x.get('catalog')) + " " + x.get('title') + " | " + str(x.get('cred')) + ' credits') data.append("-----------------------------------------") data.append("Backup courses:") for x in curs['backup_course']: data.append(" " + x.get('subject') + " " + str(x.get('catalog')) + " " + x.get('title') + " | " + str(x.get('cred')) + ' credits') except ValueError: data.append("JSON value error, possibly an empty schedule?") x = 72 y = 725 for z in range(len(data)): canvas.drawString(x, y, str(data[z])) y -= 20 if (y <= 75): canvas.showPage() y = 725 canvas.save()
def test_canvas(self): "Test generating an encrypted pdf by setting a user password on the Canvas." fname = outputfile('test_encrypt_canvas.pdf') c = Canvas(fname, encrypt='User') c.setAuthor('Anonymous') c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Top secret') c.save() parsedoc(fname)
def test_02_pageSize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas myCanvas = Canvas('demo.pdf', pagesize=A4) width, height = A4 print width, height myCanvas.drawString(width*1/3,height*2/3, "Hello World") myCanvas.showPage() myCanvas.save()
def test(self): c = Canvas(outputfile('test_hello.pdf')) #Author with Japanese text c.setAuthor('\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88') #Subject with Arabic magic c.setSubject(u'\u0643\u0644\u0627\u0645 \u0639\u0631\u0628\u064a') c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') c.save()
def test_canvas(self): "Test generating an encrypted pdf by setting a user password on the Canvas." fname = outputfile("test_encrypt_canvas.pdf") c = Canvas(fname, encrypt="User") c.setAuthor("Anonymous") c.setFont("Helvetica-Bold", 36) c.drawString(100, 700, "Top secret") c.save() parsedoc(fname)
def test_canvas(self): "Test generating an encrypted pdf by setting a user password on the Canvas." fname = outputfile('test_encrypt_canvas.pdf') c = Canvas(fname, encrypt='User') c.setAuthor('Anonymous') c.setFont('Helvetica-Bold', 36) c.drawString(100, 700, 'Top secret') c.save() parsedoc(fname)
def test1(self): import os from reportlab.lib.testutils import testsFolder filename = outputfile('test_no_helvetica.pdf') c = Canvas(filename, invariant=1, pageCompression=0, initialFontName='Times-Roman') c.drawString(100,700, 'Hello World') c.save() with open(filename, 'rb') as f: raw = f.read() assert b'Helvetica' not in raw and b'Times-Roman' in raw, 'Canvas initialFontName expectations not satisfied!'
def test(self): c = Canvas(outputfile("test_hello.pdf")) # Author with Japanese text c.setAuthor( "\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x83\xbbe\xe3\x83\x91\xe3\x83\xb3\xe3\x83\x95\xe3\x83\xac\xe3\x83\x83\xe3\x83\x88" ) # Subject with Arabic magic c.setSubject(u"\u0643\u0644\u0627\u0645 \u0639\u0631\u0628\u064a") c.setFont("Helvetica-Bold", 36) c.drawString(100, 700, "Hello World") c.save()
def test_04_canvasMethods(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch c = Canvas('demo.pdf', pagesize=A4) c.translate(inch,inch) c.setFont("Helvetica", 14) c.setAuthor("JY.zenist.song") c.setTitle("Hello ReportLib") c.drawString(3*inch, 3*inch, "Hello World") c.showPage() c.save()
def test_standardencryption(self): "Test generating an encrypted pdf by passing a StandardEncryption object to the Canvas." encrypt = pdfencrypt.StandardEncryption(userPassword='******', ownerPassword='******') encrypt.setAllPermissions(0) encrypt.canPrint = 1 fname = outputfile('test_encrypt_canvas2.pdf') c = Canvas(fname, encrypt=encrypt) c.setAuthor('Anonymous') c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Top secret') c.save() parsedoc(fname)
def test_standardencryption128(self): "Test generating an encrypted pdf by passing a StandardEncryption object to the Canvas." encrypt = pdfencrypt.StandardEncryption(userPassword="******", ownerPassword="******", strength=128) encrypt.setAllPermissions(0) encrypt.canPrint = 1 fname = outputfile("test_encrypt_canvas2_128.pdf") c = Canvas(fname, encrypt=encrypt) c.setAuthor("Anonymous") c.setFont("Helvetica-Bold", 36) c.drawString(100, 700, "More Top secret uses 128 bit encryption!") c.save() parsedoc(fname)
def _write_pdf(self, path, content): """ Write a .pdf file. Args: path (str): The file path. content (str): The file content. """ canvas = Canvas(path) canvas.drawString(12, 720, content) canvas.save()
def testSameTTFDifferentName(self): "Test PDF generation with TrueType fonts" pdfmetrics.registerFont(TTFont("Vera", "Vera.ttf")) pdfmetrics.registerFont(TTFont("MyVera", "Vera.ttf")) # Do it twice with the same font object c = Canvas(outputfile('test_pdfbase_ttfontsduplicate.pdf')) # Draw a table of Unicode characters c.setFont('Vera', 10) c.drawString(100, 700, b'Hello World') c.setFont('MyVera', 10) c.drawString(100, 688, b'Hello World') c.save()
def dumpttf(fn, fontName=None, verbose=0): """dump out known glyphs from a ttf file""" import os if not os.path.isfile(fn): raise IOError('No such file "%s"' % fn) from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen.canvas import Canvas if fontName is None: fontName = os.path.splitext(os.path.basename(fn))[0] dmpfn = "%s-ttf-dump.pdf" % fontName ttf = TTFont(fontName, fn) K = list(ttf.face.charToGlyph.keys()) registerFont(ttf) c = Canvas(dmpfn) W, H = c._pagesize titleFontSize = 30 # title font size titleFontName = "Helvetica" labelFontName = "Courier" fontSize = 10 border = 36 dx0 = stringWidth("12345: ", fontName, fontSize) dx = dx0 + 20 dy = 20 K.sort() y = 0 page = 0 for i, k in enumerate(K): if y < border: if page: c.showPage() page += 1 y = H - border - titleFontSize c.setFont(titleFontName, titleFontSize) c.drawCentredString(W / 2.0, y, "TrueType Font %s Page %d" % (fontName, page)) y -= 0.2 * titleFontSize + dy x = border c.setFont(labelFontName, 10) c.drawString(x, y, "%5.5x:" % k) c.setFont(fontName, 10) c.drawString(x + dx0, y, chr(k).encode("utf8")) x += dx if x + dx > W - border: x = border y -= dy c.showPage() c.save() if verbose: print('Font %s("%s") has %d glyphs\ndumped to "%s"' % (fontName, fn, len(K), dmpfn))
def _simple_subset_generation(fn,npages,alter=0): c = Canvas(outputfile(fn)) c.setFont('Helvetica', 30) c.drawString(100,700, 'Unicode TrueType Font Test %d pages' % npages) # Draw a table of Unicode characters for p in range(npages): for fontName in ('Vera','VeraBI'): c.setFont(fontName, 10) for i in range(32): for j in range(32): ch = utf8(i * 32 + j+p*alter) c.drawString(80 + j * 13 + int(j / 16.0) * 4, 600 - i * 13 - int(i / 8.0) * 8, ch) c.showPage() c.save()
def testTTF(self): "Test PDF generation with TrueType fonts" pdfmetrics.registerFont(TTFont("Vera", "Vera.ttf")) pdfmetrics.registerFont(TTFont("VeraBI", "VeraBI.ttf")) _simple_subset_generation('test_pdfbase_ttfonts1.pdf',1) _simple_subset_generation('test_pdfbase_ttfonts3.pdf',3) _simple_subset_generation('test_pdfbase_ttfonts35.pdf',3,5) # Do it twice with the same font object c = Canvas(outputfile('test_pdfbase_ttfontsadditional.pdf')) # Draw a table of Unicode characters c.setFont('Vera', 10) c.drawString(100, 700, b'Hello, ' + utf8(0xffee)) c.save()
def test(outDir='pdfout',shout=False): from reportlab.graphics.shapes import _baseGFontName, _baseGFontNameBI from reportlab.rl_config import verbose import os if not os.path.isdir(outDir): os.mkdir(outDir) fn = os.path.join(outDir,'renderPDF.pdf') c = Canvas(fn) c.setFont(_baseGFontName, 36) c.drawString(80, 750, 'Graphics Test') # print all drawings and their doc strings from the test # file #grab all drawings from the test module from reportlab.graphics import testshapes drawings = [] for funcname in dir(testshapes): if funcname[0:10] == 'getDrawing': drawing = eval('testshapes.' + funcname + '()') #execute it docstring = eval('testshapes.' + funcname + '.__doc__') drawings.append((drawing, docstring)) #print in a loop, with their doc strings c.setFont(_baseGFontName, 12) y = 740 i = 1 for (drawing, docstring) in drawings: assert (docstring is not None), "Drawing %d has no docstring!" % i if y < 300: #allows 5-6 lines of text c.showPage() y = 740 # draw a title y = y - 30 c.setFont(_baseGFontNameBI,12) c.drawString(80, y, 'Drawing %d' % i) c.setFont(_baseGFontName,12) y = y - 14 textObj = c.beginText(80, y) textObj.textLines(docstring) c.drawText(textObj) y = textObj.getY() y = y - drawing.height draw(drawing, c, 80, y) i = i + 1 if y!=740: c.showPage() c.save() if shout or verbose>2: print('saved %s' % ascii(fn))
def file_x(route): input_file = route output_file = route.replace("static","static_pdf") print input_file # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer footer_text = "Descargado desde https://UdpCursos.com" x = 180 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(page.BBox[2]-x, 40, footer_text) canvas.restoreState() canvas.showPage() canvas.save()
def draw_label(self, c: Canvas, col: int, row: int, redemption_code: str): x = self.left_margin + (col + 0.5) * self.label_width + col * self.inner_margin y = self.page_height - self.top_margin - (row + 0.5) * self.label_height # Drawing label bounds helps when adjusting layout. Not for production. # self.draw_label_bounds(c, x, y) c.setFont("Courier-Bold", 13) c.drawString(x - 80, y + 14, redemption_code) c.setFont("Helvetica", 10) # Space to enter redemption month and day. p = c.beginPath() p.moveTo(x + 20, y + 12) p.lineTo(x + 45, y + 12) p.moveTo(x + 55, y + 12) p.lineTo(x + 80, y + 12) p.close() c.drawPath(p) c.drawCentredString(x + 15, y + 16, 'm:') c.drawCentredString(x + 50, y + 16, 'd:') # Space to enter redeemer's email address. p = c.beginPath() p.moveTo(x - 80, y - 14) p.lineTo(x + 80, y - 14) p.close() c.drawPath(p) c.drawCentredString(x, y - 24, 'email address')