我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用reportlab.pdfgen.canvas.Canvas()。
def __init__(self, document, page, prefix, fill, start): """ Represents a page within a document that will be bates numbered. Args: document (Marisol.Document): Parent document page (PyPdf2.pdf.PageObject): PDF page associated with this page prefix (str): Bates number prefix. fill (int): Length to zero-pad number to. start (int): Number to start with. """ self.document = document self.page = page self.prefix = prefix self.fill = fill self.start = start self.height = float(self.page.mediaBox.upperRight[1]) self.width = float(self.page.mediaBox.lowerRight[0]) self.canvas_file = io.BytesIO() self.canvas = canvas.Canvas(self.canvas_file, pagesize=(self.width, self.height)) self.redactions = []
def __init__(self, pages, size=pagesizes.letter): """ Init Args: pages (int): Number of pages to mock. """ self.pages = pages self.size = size self.file = io.BytesIO() canvas = Canvas(self.file, pagesize=self.size) for page_num in range(pages): canvas.drawString(30, self.size[1]-30, "MockPDF Created By Marisol") canvas.drawString(30, self.size[1]-60, "Page {} of {}".format(page_num+1, pages)) canvas.drawString(30, self.size[1]-90, "Dimensions: {}".format(size)) canvas.showPage() canvas.save()
def position(self, c): """ Get the appropriate position on the page for the current text given an area. Args: c (canvas.Canvas): Page to get the positioning for Returns: tuple: the position """ if self.area in [Area.TOP_LEFT, Area.TOP_RIGHT]: # top from_bottom = c._pagesize[1]-15 # 15 down from height of page elif self.area in [Area.BOTTOM_LEFT, Area.BOTTOM_RIGHT]: # bottom from_bottom = 15 # 15 up from bottom of page if self.area in [Area.TOP_LEFT, Area.BOTTOM_LEFT]: # left from_left = 15 elif self.area in [Area.TOP_RIGHT, Area.BOTTOM_RIGHT]: # right offset = 15 # initial offset offset += c.stringWidth(self.text) # offset for text length from_left = c._pagesize[0]-offset return from_left, from_bottom
def apply(self, c): """ Apply the redaction to a canvas. Args: c (Canvas): canvas to apply the redaction to. """ page_width = c._pagesize[0] page_height = c._pagesize[1] c.setFont("Helvetica", 10) c.setStrokeColorRGB(*self.style.stroke) c.setFillColorRGB(*self.style.fill) c.rect(*self.position+self.size, fill=1) if self.text is not None: c.setStrokeColorRGB(*self.style.text) c.setFillColorRGB(*self.style.text) c.drawCentredString(self.center[0], self.center[1], self.text)
def main(): pdf = BytesIO() # Find all IPv6 addresses with global scope ips = [dict(a['attrs'])['IFA_ADDRESS'] for a in IPRoute().get_addr() if a['scope'] == 0 and a['family'] == 10] if ips: c = Canvas(pdf, pagesize=(PAGE_W, PAGE_H)) hello(c, 'http://[%s]/badge' % ips[0]) else: # ToDo: Legacy IP bild c = Canvas(pdf, pagesize=(PAGE_W, PAGE_H)) c.showPage() c.save() lpr = subprocess.Popen(['lpr', '-P', PRINTER], stdin=subprocess.PIPE) lpr.communicate(pdf.getvalue()) if lpr.returncode != 0: pass
def __init__(self, display_form, letter_display=None, canvas=None): self.file = io.BytesIO() self.width, self.height = letter self.canvas = canvas if not canvas: self.canvas = Canvas( self.file, pagesize=letter) self.canvas.setAuthor('Clear My Record, Code for America') self.frame = Margin( u('1in'), u('.75in'), u('1in'), u('.75in')) self.form = display_form self.letter = letter_display self.cursor = Position( self.frame.left, self.height - self.frame.top ) self.nice_date = \ self.form.date_received.get_current_value().strftime("%B %-d, %Y")
def get(self, request, *args, **kwargs): codigo = kwargs['codigo'] conformidad = ConformidadServicio.objects.get(codigo=codigo) response = HttpResponse(content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="orden_compra.pdf"' buffer = BytesIO() pdf = canvas.Canvas(buffer) self.cabecera(pdf, conformidad) y=300 self.detalle(pdf, y, conformidad) pdf.setFont("Times-Roman", 8) self.firma(pdf, 170, y-50, "GERENCIA", 120, 265, y-40) self.firma(pdf, 330, y-50, "CONFORMIDAD DEL SOLICITANTE", 320, 470, y-40) self.firma(pdf, 130, y-150, "CONFORMIDAD JEFE INMEDIATO", 120, 265, y-140) self.firma(pdf, 350, y-150, "UNIDAD DE LOGÍSTICA", 320, 470, y-140) pdf.drawCentredString(300, y-280, EMPRESA.direccion()) pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def get(self, request, *args, **kwargs): codigo = kwargs['codigo'] cotizacion = Cotizacion.objects.get(codigo=codigo) response = HttpResponse(content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="resume.pdf"' buffer = BytesIO() pdf = canvas.Canvas(buffer) self.cabecera(pdf, cotizacion) y=300 self.detalle(pdf, y, cotizacion) self.cuadro_observaciones(pdf, y, cotizacion) '''' self.firmas(pdf, y, cotizacion)''' pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): ''' This class defines the encryption properties to be used while creating a pdf document. Once initiated, a StandardEncryption object can be applied to a Canvas or a BaseDocTemplate. The userPassword parameter sets the user password on the encrypted pdf. The ownerPassword parameter sets the owner password on the encrypted pdf. The boolean flags canPrint, canModify, canCopy, canAnnotate determine wether a user can perform the corresponding actions on the pdf when only a user password has been supplied. If the user supplies the owner password while opening the pdf, all actions can be performed regardless of the flags. Note that the security provided by these encryption settings (and even more so for the flags) is very weak. ''' self.ownerPassword = ownerPassword self.userPassword = userPassword if strength == 40: self.revision = 2 elif strength == 128: self.revision = 3 self.canPrint = canPrint self.canModify = canModify self.canCopy = canCopy self.canAnnotate = canAnnotate self.O = self.U = self.P = self.key = None
def test_03_draw(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.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.rect(0.2*inch, 0.2*inch, 1*inch, 1.5*inch,fill=1) c.rotate(90) c.setFillColorRGB(0,0,0.77) c.drawString(0.3*inch, -inch, "Hello World") c.showPage() c.save()
def test_05_coordinates(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import pink, black, red, blue, green c = Canvas('demo.pdf', pagesize=A4) c.translate(inch,inch) c.setStrokeColor(pink) c.grid([1*inch,2*inch,3*inch,4*inch],[0.5*inch, 1*inch, .5*inch, 2*inch, 2.5*inch]) c.setFont("Times-Roman", 20) c.drawString(0,0, "(0,0) the Origin") c.drawString(2.5*inch, 1*inch, "(2.5,1) in inches") c.drawString(4*inch, 2.5*inch, "(4,2.5)") c.setFillColor(red) c.rect(0,2*inch,0.2*inch, 0.3*inch, fill=1) c.setFillColor(green) c.circle(4.5*inch, 0.4*inch, 0.2*inch, fill=1) c.showPage() c.save()
def get_reg_note(request): reg_details = get_object_or_404(RegDetails, pk=request.GET.get('reg', '')) try: invoice = Invoice.objects.get(reg_details=reg_details) except Invoice.DoesNotExist: invoice = None inv_num = str(invoice.pk) if invoice else 'free' file_details = 'inline; filename="reg_note_' + inv_num + '"' response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = file_details buffr = BytesIO() note_pdf = canvas.Canvas(buffr, pagesize=letter) generate_reg_note(note_pdf, reg_details, invoice) note_pdf.showPage() note_pdf.save() pdf = buffr.getvalue() buffr.close() response.write(pdf) return response
def gen_team_pdf(team_tuples: list): global _reged if not _reged: pdfmetrics.registerFont(TTFont('my_font', options.options.ttf_font_name)) _reged = True buf = io.BytesIO() canv = canvas.Canvas(buf, pagesize=A4_TRANSVERSE) style = ParagraphStyle(name='default', fontName='my_font', fontSize=options.options.pdf_font_size, alignment=1, leading=options.options.pdf_font_size * 1.2) for index, team in team_tuples: paragraph = Paragraph('Team {0}<br />{1}'.format(index, team['team_name']), style) w, h = paragraph.wrap(A4_TRANSVERSE[0] - 50, A4_TRANSVERSE[1] - 50) paragraph.drawOn(canv, (A4_TRANSVERSE[0] - w) / 2, (A4_TRANSVERSE[1] - h) / 2) canv.showPage() canv.save() return buf.getvalue()
def render(self, out): el = self.dom.documentElement.getElementsByTagName('docinit') if el: self.docinit(el) el = self.dom.documentElement.getElementsByTagName('stylesheet') self.styles = _rml_styles(el) el = self.dom.documentElement.getElementsByTagName('template') if len(el): pt_obj = _rml_template(out, el[0], self) pt_obj.render(self.dom.documentElement.getElementsByTagName('story')[0]) else: self.canvas = canvas.Canvas(out) pd = self.dom.documentElement.getElementsByTagName('pageDrawing')[0] pd_obj = _rml_canvas(self.canvas, None, self) pd_obj.render(pd) self.canvas.showPage() self.canvas.save()
def __init__(self, text=[], target='your website', pdfName='Report.pdf'): self.__target = target self.__pdfName = self.__path + pdfName self.__text = text if not os.path.exists('result/'): os.mkdir(r'result/') time = datetime.datetime.today() date = time.strftime("%h-%d-%Y %H:%M:%S") c = canvas.Canvas(self.__pdfName) c.setPageSize((16 * inch,22 * inch)) textobj = c.beginText() textobj.setTextOrigin(inch, 20 * inch) textobj.textLines(''' This is the scanning report of %s. ''' %self.__target) textobj.textLines(''' Date: %s ''' % date) for line in self.__text: textobj.textLine(line.strip()) c.drawText(textobj) c.showPage() c.save()
def test_draw(self): canvas = Canvas(None) p1 = rpara(self.text, S) p2 = rpara(self.text, S) cell = Cell([p1, p2], S.set(padding_left=1, padding_top=3, padding_bottom=3)) # natural height, aligned top cell.wrap(30) cell.drawOn(canvas, 0, 0) self.assertEqual(p1.draw_call, (1, 17)) self.assertEqual(p2.draw_call, (1, 3)) # force different height cell.height = 100 cell.drawOn(canvas, 0, 0) self.assertEqual(p1.draw_call, (1, 83)) self.assertEqual(p2.draw_call, (1, 69)) # height 100 and aligned to bottom cell.style = cell.style.set(vertical_align=VerticalAlign.bottom) cell.drawOn(canvas, 0, 0) self.assertEqual(p1.draw_call, (1, 17)) self.assertEqual(p2.draw_call, (1, 3)) # middle aligned cell.style = cell.style.set(vertical_align=VerticalAlign.middle) cell.drawOn(canvas, 0, 0) self.assertEqual(p1.draw_call, (1, 50)) self.assertEqual(p2.draw_call, (1, 36))
def getPdf(self,aMsg): c = canvas.Canvas(None) c.drawString(100,100,aMsg) c.showPage() c.save() return xmlrpclib.Binary(c.getpdfdata())
def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = []
def save(self): """add page info to each page (page x of y)""" num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self)
def apply(self, c): """ Applies the bates number to a canvas. Args: c (canvas.Canvas): canvas to apply the overlay to """ position_left, position_bottom = self.position(c) c.drawString(position_left, position_bottom, self.text)
def save(self): '''add page info to each page (page x of y)''' num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self)
def __init__( self, data_dir, uid, out_dir=None, filename=None, load=True, user=None, report_type='saxs',md=None ): self.data_dir = data_dir self.uid = uid self.md = md #print(md) if user is None: user = 'chx' self.user = user if out_dir is None: out_dir = data_dir if not os.path.exists(out_dir): os.makedirs(out_dir) self.out_dir=out_dir self.styles = getSampleStyleSheet() self.width, self.height = letter self.report_type = report_type dt =datetime.now() CurTime = '%02d/%02d/%s/-%02d/%02d/' % ( dt.month, dt.day, dt.year,dt.hour,dt.minute) self.CurTime = CurTime if filename is None: filename="XPCS_Analysis_Report_for_uid=%s.pdf"%uid filename=out_dir + filename c = canvas.Canvas( filename, pagesize=letter) self.filename= filename #c.setTitle("XPCS Analysis Report for uid=%s"%uid) c.setTitle(filename) self.c = c if load: self.load_metadata()
def generate_document(self, data): packet = StringIO() if self.template_file is not None: template = PdfFileReader(open(self.template_file, 'rb')) c = canvas.Canvas(packet, pagesize=(self.width, self.height)) i = 0 for field_cls in self.fields: # TODO: Catch exception if there is less columns than fields field = field_cls(self, c, data[i]) field.render() i += 1 # Save canvas c.save() packet.seek(0) text = PdfFileReader(packet) output = PdfFileWriter() if self.template_file is not None: # Merge text with base page = template.getPage(0) page.mergePage(text.getPage(0)) else: page = text.getPage(0) output.addPage(page) # Save file filename = "%s/%s.pdf" % (self.output_dir, self.generate_filename(data)) outputStream = open(filename, 'wb') output.write(outputStream) outputStream.close()
def fits(self, flowables): story = flowables self.resize_images(story) W, H = ( self.width - self.lm - self.rm), self.height - self.tm - self.bm canv = Canvas(io.StringIO(), (W, H)) total_height = sum([el.wrapOn(canv, W, 0)[1] + bt.spaceBefore for el in story]) if getattr(self, "verbose", False) == True: print("***", total_height / mm, H / mm, \ [txt.text[:5] for txt in story]) return total_height < H
def overlay_hocr_page(self, dpi, hocr_filename, img_filename): hocr_dir, hocr_basename = os.path.split(hocr_filename) img_dir, img_basename = os.path.split(img_filename) logging.debug("hocr_filename:%s, hocr_dir:%s, hocr_basename:%s" % (hocr_filename, hocr_dir, hocr_basename)) assert(img_dir == hocr_dir) #basename = hocr_basename.split('.')[0] basename = os.path.splitext(hocr_basename)[0] pdf_filename = os.path.join("text_%s_ocr.pdf" % (basename)) # Switch to the hocr directory to make this easier cwd = os.getcwd() if hocr_dir != "": os.chdir(hocr_dir) with open(pdf_filename, "wb") as f: logging.info("Overlaying hocr and creating text pdf %s" % pdf_filename) pdf = Canvas(f, pageCompression=1) pdf.setCreator('pypdfocr') pdf.setTitle(os.path.basename(hocr_filename)) pdf.setPageCompression(1) width, height, dpi_jpg = self._get_img_dims(img_basename) pdf.setPageSize((width,height)) logging.info("Page width=%f, height=%f" % (width, height)) pg_num = 1 logging.info("Adding text to page %s" % pdf_filename) self.add_text_layer(pdf,hocr_basename,pg_num,height,dpi) pdf.showPage() pdf.save() os.chdir(cwd) return os.path.join(hocr_dir, pdf_filename)
def get(self, request, *args, **kwargs): codigo = kwargs['pk'] orden = OrdenCompra.objects.get(pk=codigo) response = HttpResponse(content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="orden_compra.pdf"' buffer = BytesIO() pdf = canvas.Canvas(buffer) self.cabecera(pdf, orden) y=300 self.detalle(pdf, y, orden) self.otros(pdf, y, orden) self.cuadro_total(pdf, y, orden) self.cuadro_observaciones(pdf, y, orden) self.afectacion_presupuesta(pdf) pdf.setFont("Times-Roman", 8) pdf.drawString(115, y-250,"Elaborado por") pdf.drawString(430, y-250,"Autorizado por") pdf.line(70, y-240, 200, y-240) pdf.line(390, y-240, 520, y-240) pdf.drawCentredString(300, y-280, EMPRESA.direccion()) pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def get(self, request, *args, **kwargs): codigo = kwargs['codigo'] orden = OrdenServicios.objects.get(codigo=codigo) response = HttpResponse(content_type='application/pdf') #response['Content-Disposition'] = 'attachment; filename="orden_compra.pdf"' buffer = BytesIO() pdf = canvas.Canvas(buffer) self.cabecera(pdf, orden) y=300 self.detalle(pdf, y, orden) self.otros(pdf, y, orden) self.cuadro_total(pdf, y, orden) self.cuadro_observaciones(pdf, y, orden) self.afectacion_presupuesta(pdf) pdf.setFont("Times-Roman", 8) pdf.drawString(115, y-250,"Elaborado por") pdf.drawString(430, y-250,"Autorizado por") pdf.line(70, y-240, 200, y-240) pdf.line(390, y-240, 520, y-240) pdf.drawCentredString(300, y-280, EMPRESA.direccion()) pdf.showPage() pdf.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def BurnSudoOnPdf(path,numpage,diffarray): pdf = PdfFileWriter() # Using ReportLab Canvas to insert image into PDF imgTemp = BytesIO() imgDoc = canvas.Canvas(imgTemp, pagesize=A4) # Draw image on Canvas and save PDF in buffer pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) for i in range(len(path)): if ((i+1)%2==0): x=345 else: x=55 if (i<2): y=590 elif (i<4): y=320 else: y=50 imgDoc.drawImage(path[i], x, y,200,200) imgDoc.setFont('VeraIt', 9) imgDoc.drawString(x+2,y+203,getStrDiff(diffarray[i])) pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) #pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) imgDoc.setFont('Vera', 13) imgDoc.drawString(30,820,"BurnYourPc Organization/") imgDoc.setFont('VeraBd', 9) imgDoc.drawString(197,820,"Sudoku Project") imgDoc.setFont('VeraIt', 8) imgDoc.drawString(430,20,"By PantelisPanka, nikfot, TolisChal") imgDoc.setFont('Vera', 8) imgDoc.drawString(550,820,str(numpage)) imgDoc.save() # Use PyPDF to merge the image-PDF into the template pdf.addPage(PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0)) pdf.write(open("output"+ str(numpage)+".pdf","wb"))
def RenderToIo(boards, write_target): """Renders the given boards to the passed output stream.""" c = canvas.Canvas(write_target, pagesize=LETTER) for board in boards: _BoardRenderer(board, c).Render() c.save()
def _startBuild(self, filename=None, canvasmaker=canvas.Canvas): self._calc() #each distinct pass gets a sequencer self.seq = reportlab.lib.sequencer.Sequencer() self.canv = canvasmaker(filename or self.filename, pagesize=self.pagesize, invariant=self.invariant, pageCompression=self.pageCompression, enforceColorSpace=self.enforceColorSpace, initialFontName = self.initialFontName, initialFontSize = self.initialFontSize, initialLeading = self.initialLeading, cropBox = self.cropBox, artBox = self.artBox, trimBox = self.trimBox, bleedBox = self.bleedBox, ) getattr(self.canv,'setEncrypt',lambda x: None)(self.encrypt) self.canv._cropMarks = self.cropMarks self.canv.setAuthor(self.author) self.canv.setTitle(self.title) self.canv.setSubject(self.subject) self.canv.setCreator(self.creator) self.canv.setKeywords(self.keywords) if self.displayDocTitle is not None: self.canv.setViewerPreference('DisplayDocTitle',['false','true'][self.displayDocTitle]) if self.lang: self.canv.setCatalogEntry('Lang',self.lang) if self._onPage: self.canv.setPageCallBack(self._onPage) self.handle_documentBegin()
def test(): from pprint import pprint #print test_program; return from reportlab.pdfgen import canvas from reportlab.lib.units import inch fn = "paratest0.pdf" c = canvas.Canvas(fn) test2(c,testparagraph) test2(c,testparagraph1) if 1: remainder = test_program + test_program + test_program laststate = {} while remainder: print("NEW PAGE") c.translate(inch, 8*inch) t = c.beginText() t.setTextOrigin(0,0) p = paragraphEngine() p.resetState(laststate) p.x = 0 p.y = 0 maxwidth = 7*inch maxheight = 500 (formattedprogram, remainder, laststate, height) = p.format(maxwidth, maxheight, remainder) if debug: pprint( formattedprogram )#; return laststate = p.runOpCodes(formattedprogram, c, t) c.drawText(t) c.showPage() print("="*30, "x=", laststate["x"], "y=", laststate["y"]) c.save() print(fn)
def rotate(self, theta): """Canvas.rotate(theta) Rotate the canvas by the angle theta (in degrees).""" c = cos(theta * pi / 180) s = sin(theta * pi / 180) self.transform(c, s, -s, c, 0, 0)
def encryptPdfInMemory(inputPDF, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """accepts a PDF file 'as a byte array in memory'; return encrypted one. This is a high level convenience and does not touch the hard disk in any way. If you are encrypting the same file over and over again, it's better to use pageCatcher and cache the results.""" try: from rlextra.pageCatcher.pageCatcher import storeFormsInMemory, restoreFormsInMemory except ImportError: raise ImportError('''reportlab.lib.pdfencrypt.encryptPdfInMemory failed because rlextra cannot be imported. See https://www.reportlab.com/downloads''') (bboxInfo, pickledForms) = storeFormsInMemory(inputPDF, all=1, BBoxes=1) names = list(bboxInfo.keys()) firstPageSize = bboxInfo['PageForms0'][2:] #now make a new PDF document buf = getBytesIO() canv = Canvas(buf, pagesize=firstPageSize) # set a standard ID while debugging if CLOBBERID: canv._doc._ID = "[(xxxxxxxxxxxxxxxx)(xxxxxxxxxxxxxxxx)]" encryptCanvas(canv, userPassword, ownerPassword, canPrint, canModify, canCopy, canAnnotate, strength=strength) formNames = restoreFormsInMemory(pickledForms, canv) for formName in formNames: canv.setPageSize(bboxInfo[formName][2:]) canv.doForm(formName) canv.showPage() canv.save() return buf.getvalue()
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 test() : """Test this.""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib import pagesizes canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) canvas.setFont("Helvetica", 30) (width, height) = pagesizes.A4 canvas.drawCentredString(width/2.0, height-4*cm, "Sample LTO labels") xpos = xorig = 2 * cm ypos = yorig = 2 * cm colwidth = 10 * cm lineheight = 3.9 * cm count = 1234 BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 BaseLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", colored=True).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125, colored=True).drawOn(canvas, xpos, ypos) canvas.showPage() canvas.save()
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 __init__(self, page_size): self._file = BytesIO() self.canvas = Canvas(self._file, pagesize=page_size) self._saved = False
def producePrintoutsForLayer(base_name, layer, canv): ctmp = canvas.Canvas(base_name + "_assy.pdf") ext = renderGerber(base_name, layer, ctmp); scale1 = (gerberPageSize[0]-2*gerberMargin)/((ext[2]-ext[0])) scale2 = (gerberPageSize[1]-2*gerberMargin)/((ext[3]-ext[1])) scale = min(scale1, scale2) gerberScale = (scale,scale) # print("PS" , gerberPageSize[0], gerberMargin, gerberScale) gerberOffset = (-ext[0]*scale + gerberMargin, -ext[1]*scale + gerberMargin) # print "Offset (in.): (%4.2f, %4.2f)" % (gerberOffset[0]/inch,gerberOffset[1]/inch) # print "Scale (in.): (%4.2f, %4.2f)" % gerberScale pf = PickAndPlaceFileKicad(base_name+".CSV") ngrp = pf.num_groups(layer) for page in range(0, (ngrp+5)/6): n_comps = min(6, ngrp - page*6) canv.saveState() canv.translate( gerberOffset[0], gerberOffset[1] ) if(layer == "Bottom"): canv.scale( gerberScale[0], gerberScale[1] ) # canv.scale( -1, 1 ) # canv.translate(-0.5*gerberPageSize[0],0) else: canv.scale( gerberScale[0], gerberScale[1] ) renderGerber(base_name, layer, canv); pf.draw(layer, page*6, n_comps, canv); canv.restoreState() pf.gen_table(layer, page*6, n_comps, canv); canv.showPage()
def __init__(self, fileName, canv=None): from reportlab.pdfgen import canvas if(canv == None): self.canv = canvas.Canvas(fileName, pagesize=gerberPageSize, pageCompression = 1 ) else: self.canv = canv self.Initialize() # }}} # {{{ Initialize
def test_01_start(self): from reportlab.pdfgen import canvas c = canvas.Canvas("demo.pdf") c.drawString(100,100, "Hello World") c.showPage() c.save()
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_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_07_registerFont(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont('chsFont', 32) c.drawString(0,0,"??????????") c.showPage() c.save()
def process_pdf(self, image_data, hocr_data, pdf_filename): """Utility function if you'd rather get the PDF data back instead of save it automatically.""" pdf = Canvas(pdf_filename, pageCompression=1) pdf.setCreator('hocr-tools') pdf.setPageSize((self.width, self.height)) pdf.drawImage(image_data, 0, 0, width=self.width, height=self.height) pdf = self.add_text_layer(pdf, hocr_data) pdf_data = pdf.getpdfdata() return pdf_data