def drawline(self,time_axis,para,filename): self.lp.data = [zip(time_axis,para)] self.drawing.add(self.lp) self.drawing.add(self.title) self.drawing.add(self.Xlabel) self.drawing.add(self.Ylabel) renderPDF.drawToFile(self.drawing,filename,'Sunspots')
def test03(): # 最终太阳黑子图形程序 from urllib import urlopen from reportlab.graphics.shapes import * from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.charts.textlabels import Label from reportlab.graphics import renderPDF URL = "http://services.swpc.noaa.gov/text/predicted-sunspot-radio-flux.txt" COMMENT_CHARS = "#:" drawing = Drawing(400, 200) data = [] for line in urlopen(URL).readlines(): if not line.isspace() and not line[0] in COMMENT_CHARS: data.append([float(n) for n in line.split()]) pred = [row[2] for row in data] high = [row[3] for row in data] low = [row[4] for row in data] times = [row[0] + row[1] / 12.0 for row in data] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [zip(times, pred), zip(times, high), zip(times, low)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green drawing.add(lp) drawing.add(String(250, 150, "Sunsports", fontSize=14, fillColor=colors.red)) renderPDF.drawToFile(drawing, "report2.pdf", "Sunsports")
def main(): URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt' COMMENT_CHARS = '#:' drawing = Drawing(400, 200) data = [] for line in urlopen(URL).readlines(): if not line.isspace() and not line[0] in COMMENT_CHARS: data.append([float(n) for n in line.split()]) pred = [row[2] for row in data] high = [row[3] for row in data] low = [row[4] for row in data] times = [row[0] + row[1]/12.0 for row in data] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [zip(times, pred), zip(times, high), zip(times, low)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green drawing.add(lp) drawing.add(String(250, 150, 'Sunspots', fontSize = 14, fillColor = colors.red)) renderPDF.drawToFile(drawing, 'report.pdf', 'Sunspots')
def main(genes, hmmMatches1, hmmMatches2, hsps, cluster, window): drawing = Drawing(window.xsize, window.ysize) y = 50 xmap = Mapping(margin,window.xsize-margin,window.start,window.end) addAxis(drawing, xmap, y) for f in genes: if f.chrom==window.chrom and \ (window.start<=f.start<=window.end or \ window.start<=f.end<=window.end): addGene(drawing, xmap, y+20, f, fillColor=colors.blue) # for f in hmmMatches1: # if f.chrom==window.chrom and \ # (window.start<=f.start<=window.end or \ # window.start<=f.end<=window.end): # addGene(drawing, xmap, y+120, f, fillColor=colors.green) # # for f in hmmMatches2: # if f.chrom==window.chrom and \ # (window.start<=f.start<=window.end or \ # window.start<=f.end<=window.end): # addGene(drawing, xmap, y+200, f, fillColor=colors.green) # # for f in hsps: # if f.chrom==window.chrom and \ # (window.start<=f.start<=window.end or \ # window.start<=f.end<=window.end): # addGene(drawing, xmap, y+280, f, fillColor=colors.red) # oFilename = 'diagramsWithFeatures/%s.pdf' % cluster oFilename = '%s.pdf' % cluster renderPDF.drawToFile(drawing, oFilename, '') os.system('open %s' % oFilename)
def create_preamble(name, style, logo): if ".svg" in logo: #check if the logo is in svg format tempf = open(logo, 'r') #open the file for reading s = tempf.read() height_k = re.search('height=\"(\d*).(\d*)', s) #get the height of the picture, using regular expressions height_l = float(re.search('\"(\d*).(\d*)', height_k.group(0)).group(0)[1:]) #get only the height width_k = re.search('width=\"(\d*).(\d*)', s) #get the width of the picture, using regular expressions width_l = float(re.search('\"(\d*).(\d*)', width_k.group(0)).group(0)[1:]) #get only the width drawing = svg2rlg(logo) #draw the picture logo = logo.replace(".svg", ".pdf") #replace the .svg part with .pdf renderPDF.drawToFile(drawing, "temp/" + logo[logo.rfind("/") + 1:]) #draw the picture to the file and render it else: width_l, height_l = Image.open(logo).size if(os.path.isfile(logo)): shutil.copy(logo, "temp/" + logo[logo.rfind("/") + 1:]) logo = logo[logo.rfind("/") + 1:] scale_height = 622.519685 / height_l scale_width = 418.110236 / width_l scale = (min(scale_height, scale_width)) #calculate how much the logo can be scaled f = open("Resources/SongBookletTemplate.tex", 'r', encoding = 'utf-8') #now create the tex file for the songbook itself tex = f.read() f.close() return tex.replace("***NAME***", name).replace("***LOGO***", logo).replace("***NUMBERING***", style).replace("***SCALE***", str(scale * 0.4))
def test1_main(): d = Drawing(100, 100) s = String(50, 50, 'BP_project2', textAnchor = 'middle') d.add(s) renderPDF.drawToFile(d, 'test_out.pdf', 'a simple PDF file')
def drawdata(data, times, labels): drawing = Drawing(10000, 200) fontstep = 5.5 for i in range(0, size(labels)): drawing.add(String(40,(i+9.8)*fontstep,str(labels[i]), textAnchor="middle", fontSize=5)) #drawing.add(String(20,175,"labels", textAnchor="middle", fontSize=5)) #data = [1, 2, 3, 4, 5, 6] lc = HorizontalLineChart() #lc.valueAxis = 0 lc.x = 50 lc.y = 50 lc.height = 155 lc.width = 10000 lc.data = data lc.joinedLines = 1 #catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') #catNames = times #lc.categoryAxis.categoryNames = catNames #lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.visible = 0 fontstep = 40 for i in range(0, size(times)): drawing.add(String((i+1.3)*fontstep,45,str(times[i]), textAnchor="middle", fontSize=5)) lc.lineLabelArray = ['1','2'] #lc.valueAxis.valueMin = 0 #lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 1 #lc.valueAxis.valueSteps = [1, 2, 3, 5, 6] lc.lines[0].strokeWidth = .5 lc.lines[1].strokeWidth = .5 drawing.add(lc) renderPDF.drawToFile(drawing, 'example1.pdf', 'EEG data') return drawing, lc
def test2_main(): data = [ (2012,12,61.2,62.2,60.2), (2013,1,63.2,65.2,61.2), (2013,2,65.3,68.3,62.3), (2013,3,67.5,72.5,62.5), (2013,4,70.1,75.1,65.1), (2013,5,72.7,78.7,66.7), (2013,6,75.7,82.7,68.7), (2013,7,78.6,85.6,71.6), (2013,8,81.6,89.6,73.6), (2013,9,84.7,93.7,75.7) ] drawing = Drawing(4000, 150) pred = [row[2] - 40 for row in data] high = [row[3] - 40 for row in data] low = [row[4] - 40 for row in data] times = [200 * ((row[0] + row[1]/12.0) - 2007) - 110 for row in data] print(times) print(pred) print(high) drawing.add(PolyLine(zip(times, pred), strokeColor = colors.blue)) drawing.add(PolyLine(zip(times, high), strokeColor = colors.red)) drawing.add(PolyLine(zip(times, low), strokeColor = colors.green)) drawing.add(String(65, 115, 'Sunspots', fontSize = 18, fillColor = colors.red)) renderPDF.drawToFile(drawing, 'report.pdf', 'Sunspots')
def save(self, file=None, format=None): """Hand this either a file= <filename> or file = <an open file object>. """ if not file: file = self.name from reportlab.graphics import renderPDF renderPDF.drawToFile(self.drawing, file, self.name)
def test_12_drawingRenderPDF(self): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Rect from reportlab.graphics import renderPDF d = Drawing(400,200) d.add(Rect(50,50,300,100, fillColor=colors.yellow)) renderPDF.drawToFile(d, 'demo.pdf', 'JY.zenist.song')
def test01(): # 生成 hello world 的PDF import reportlab.graphics.shapes as Rshape import reportlab.graphics.renderPDF as RrenderPDF d = Rshape.Drawing(100, 100) s = Rshape.String(50, 50, "Hello world!", textAnchor="middle") d.add(s) RrenderPDF.drawToFile(d, "hello.pdf", "A simple PDF file")
def draw(): ''' data=[(2007,8,113.2,114.2,112.2), (2007,9,112.8,115.8,109.8), (2007,10,111.0,116.0,106.0), (2007,11,109.8,116.8,102.8), (2007,12,107.3,115.3,99.3), (2008,1,105.2,114.2,96.2), (2008,2,104.1,114.1,94.1), (2008,3,99.9,110.9,88.9), (2008,4,94.8,106.8,82.8), (2008,5,91.2,104.2,78.2)] ''' ''' #这个是在pdf里画一个 hello word 的例子, d=Drawing(100,100) s=String(50,50,"hello word",textAnchor="middle") d.add(s) renderPDF.drawToFile(d,"hello.pdf","A simple PDF file")#renderPDF.drawToFile调用后会把你的pdf文件存到当前目录下一个叫hello.pdf的文件中 ''' URL="http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt"#见364页,这个网址记录的是太阳黑子的全部数据 COMMENT_CHARS="#:" drawing=Drawing(400,200) data=[] for line in urlopen(URL).readlines(): #not isspace()是判断 这一行不为空字符串,not line[0] in COMMENT_CHARS是说 在网页里去掉 # 和 . 的部分 if not line.isspace() and not line[0] in COMMENT_CHARS: data.append([float(n) for n in line.split()]) #print data pred=[row[2] for row in data] high=[row[3] for row in data] low=[row[4] for row in data] times=[row[0]+row[1]/12.0 for row in data] lp=LinePlot() #设置 x,y,height,width,以及data lp.x=50 lp.y=50 lp.height=125 lp.width=300 lp.data=[zip(times,pred),zip(times,high),zip(times,low)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green ''' drawing.add(PolyLine(zip(times,pred),storkeColor=colors.blue)) drawing.add(PolyLine(zip(times,high),storkeColor=colors.red)) drawing.add(PolyLine(zip(times,low),storkeColor=colors.green)) #drawing.add(PolyLine([(10,50),(100,50),(80,80)],storkeColor=colors.red))#这个是直接画一条线 ''' drawing.add(lp) drawing.add(String(250,150,"SunSpots",fontSize=14,fillColor=colors.red)) renderPDF.drawToFile(drawing,"report.pdf","SunSpots")#renderPDF.drawToFile调用后会把你的pdf文件存到当前目录下一个叫report.pdf的文件中
def visit_image(self, aa_image): """Process the given ASCIIArtFigure and output the shapes in the PDF file """ self.aa_image = aa_image # save for later XXX not optimal to do it here self.width = (aa_image.width)*aa_image.nominal_size*aa_image.aspect_ratio self.height = (aa_image.height)*aa_image.nominal_size self.drawing = Drawing(self._num(self.width), self._num(self.height)) self.visit_shapes(aa_image.shapes) renderPDF.drawToFile(self.drawing, self.file_like, '')
def test(): """This function produces three pdf files with examples of all the signs and symbols from this file. """ # page 1 labelFontSize = 10 X = (20,245) flags = [ 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'Denmark', 'Cuba', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil', ] y = Y0 = 530 f = 0 D = None for name in flags: if not D: D = Drawing(450,650) flag = makeFlag(name) i = flags.index(name) flag.x = X[i%2] flag.y = y D.add(flag) D.add(String(flag.x+(flag.size/2),(flag.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) if i%2: y = y - 125 if (i%2 and y<0) or name==flags[-1]: renderPDF.drawToFile(D, 'flags%02d.pdf'%f, 'flags.py - Page #%d'%(f+1)) y = Y0 f = f+1 D = None
def print_100(file): d = Drawing(1000,1000) with open(file, 'rb') as f: for _ in range(3): print(f.readline().decode('utf-8')) sentence = str(f.readline().decode('utf-8')) s = String(10,10, sentence) d.add(s) renderPDF.drawToFile(d, 'test.pdf', 'A simple PDF file')
def __del__(self): if IMAGES[-1] != None: return else: del IMAGES[-1] d = Drawing(A4[0], A4[1]) for img in IMAGES: d.add(img) outPath = outputfile("test_graphics_images.pdf") renderPDF.drawToFile(d, outPath) #, '') assert os.path.exists(outPath) == 1
def render_multipage(drawing, opts, outbuf=None): if opts.pagesize in name2size: pagesize = name2size[opts.pagesize] else: pagesize = opts.pagesize or letter border = opts.border or 1*cm landscape = opts.landscape or False pgwidth, pgheight = pagesize if not landscape \ else (pagesize[1], pagesize[0]) #print "drawing width, height:", drawing.width/inch, drawing.height/inch if drawing.width > pgwidth - 2*border: scalefact = (pgwidth - 2*border)/float(drawing.width) drawing.scale(scalefact, scalefact) else: scalefact = 1.0 #border *= scalefact dwidth = drawing.width*scalefact dheight = drawing.height*scalefact output = PdfFileWriter() if not outbuf: outfile = file(opts.outfile, "wb") else: outfile = outbuf buf = StringIO() renderPDF.drawToFile(drawing, buf) lower = dheight pgnum = 0 while lower >= 0: if pgnum == 0: delta = 0.0 else: delta = 2*border*pgnum buf.seek(0) tmp = PdfFileReader(buf) page = tmp.getPage(0) box = page.mediaBox uly = float(box.getUpperLeft_y()) * scalefact upper = uly+border+delta-pgnum*pgheight #lower = uly+border+delta-(pgnum+1)*pgheight lower = upper-pgheight box.setUpperRight((pgwidth-border, upper)) box.setUpperLeft((-border, upper)) box.setLowerRight((pgwidth-border, lower)) box.setLowerLeft((-border, lower)) output.addPage(page) pgnum += 1 output.write(outfile) return pgnum, scalefact
def test_convert_pdf(self): "Test convert sample SVG files to PDF using svglib." paths = glob.glob("%s/samples/misc/*" % TEST_ROOT) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print("working on [%d] %s" % (i, path)) # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0)
def test0(self): "Test converting flag SVG files to PDF using svglib." paths = glob.glob("%s/*" % self.folderPath) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print("working on [%d]" % i, path) # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0)
def MakePDF(times, list, reportname, pdfname): drawing = Drawing(500, 300) lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [zip(times, list)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green drawing.add(lp) drawing.add(String(350, 150, reportname, fontSize=14, fillColor=colors.red)) renderPDF.drawToFile(drawing, pdfname, reportname)
def test02(): data = data0 # 太阳黑子图形程序的第一个原型 from reportlab.lib import colors from reportlab.graphics import renderPDF from reportlab.graphics.shapes import * drawing = Drawing(200, 150) pred = [row[2] - 40 for row in data] high = [row[3] - 40 for row in data] low = [row[4] - 40 for row in data] times = [200 * ((row[0] + row[1] / 12.0) - 2015) - 110 for row in data] drawing.add(PolyLine(zip(times, pred), strokeColor=colors.blue)) drawing.add(PolyLine(zip(times, high), strokeColor=colors.red)) drawing.add(PolyLine(zip(times, low), strokeColor=colors.green)) drawing.add(String(65, 115, "Sunsports", fontSize=18, fillColor=colors.red)) renderPDF.drawToFile(drawing, "report1.pdf", "Sunsports")
def test_convert_pdf_png(self): """ Test converting W3C SVG files to PDF and PNG using svglib. ``renderPM.drawToFile()`` used in this test is known to trigger an error sometimes in reportlab which was fixed in reportlab 3.3.26. See https://github.com/deeplook/svglib/issues/47 """ exclude_list = [ "paint-stroke-06-t.svg", "coords-trans-09-t.svg", # renderPDF issue (div by 0) # Unsupported 'transform="ref(svg, ...)"' expression "coords-constr-201-t.svg", "coords-constr-202-t.svg", "coords-constr-203-t.svg", "coords-constr-204-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folder_path) msg = "Destination folder '%s/svg' not found." % self.folder_path assert len(paths) > 0, msg for i, path in enumerate(paths): print("working on [%d] %s" % (i, path)) if basename(path) in exclude_list: print("excluded (to be tested later)") continue # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0) # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: # Can trigger an error in reportlab < 3.3.26. renderPM.drawToFile(drawing, base, 'PNG') except TypeError: print('Svglib: Consider upgrading reportlab to version >= 3.3.26!') raise
def render_pdf(drawing, opts): width = drawing.width height = drawing.height border = opts.border or 1*cm drawing.width += 2*border drawing.height += 2*border drawing.translate(border, border) #avail_w = size[0] - 2*border; avail_h = size[1] - 2*border #scalefact = min(avail_w/float(width), avail_h/float(height)) #drawing.scale(scalefact, scalefact) ## size = (width+2*border, height+2*border) ## canvas = reportlab.pdfgen.canvas.Canvas(opts.outfile, size) ## canvas.setFont("Times-Roman", 10) ## drawing.drawOn(canvas, border, border) ## canvas.showPage() ## canvas.save() buf = StringIO() renderPDF.drawToFile(drawing, buf) return buf
def saveQrCodeSVG(filename,text, ptext): factory = qrcode.image.svg.SvgPathImage img = qrcode.make(text, image_factory=factory,box_size=30, border=4) svf = open(filename,"w") img.save(svf,"SVG") svf.close() text_svg_fname = filename+".text.svg" merged_svg_name = filename+'.merged.svg' svg_document = svgwrite.Drawing(filename = text_svg_fname, size = ("41mm", "41mm")) # svg_document.add(svg_document.rect(insert = (0, 0), # size = ("41mm", "41mm"), # stroke_width = "1", # stroke = "black", # fill = "rgb(240,240,240)")) svg_document.add(svg_document.text(ptext, insert = (106, 10), fill = "rgb(0,0,0)", style = "font-size:1mm; font-family:Arial")) svg_document.add(svg_document.text(text, insert = (7.5, 117), fill = "rgb(0,0,0)", style = "font-size:1.8mm; font-family:Arial")) svg_document.save() # dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red')) # ##PDF # drawing = svg2rlg(filename) # renderPDF.drawToFile(drawing, filename+".pdf") template = st.fromfile(text_svg_fname) second_svg = st.fromfile(filename) template.append(second_svg) template.save(merged_svg_name) drawing = svg2rlg(merged_svg_name) renderPDF.drawToFile(drawing, filename+".pdf")
def test(): from reportlab.graphics.charts.piecharts import WedgeProperties wedges = TypedPropertyCollection(WedgeProperties) wedges.fillColor = colors.red wedges.setVector(fillColor=(colors.blue,colors.green,colors.white)) print(len(_ItemWrapper)) d = shapes.Drawing(400, 200) tc = TwoCircles() d.add(tc) from reportlab.graphics import renderPDF renderPDF.drawToFile(d, 'sample_widget.pdf', 'A Sample Widget') print('saved sample_widget.pdf') d = shapes.Drawing(400, 200) f = Face() f.skinColor = colors.yellow f.mood = "sad" d.add(f, name='theFace') print('drawing 1 properties:') d.dumpProperties() renderPDF.drawToFile(d, 'face.pdf', 'A Sample Widget') print('saved face.pdf') d2 = d.expandUserNodes() renderPDF.drawToFile(d2, 'face_copy.pdf', 'An expanded drawing') print('saved face_copy.pdf') print('drawing 2 properties:') d2.dumpProperties()
def test0(self): "Test sample SVG files included in svglib test suite." paths = glob.glob("samples/misc/*") paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print "working on [%d]" % i, path # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path
def test0(self): "Test converting symbol SVG files to PDF using svglib." paths = glob.glob("%s/*" % self.folderPath) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print "working on [%d]" % i, path # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path
def test0(self): "Test converting W3C SVG files to PDF using svglib." excludeList = [ "paint-stroke-06-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folderPath) msg = "Destination folder '%s/svg' not found." % self.folderPath self.failUnless(len(paths) > 0, msg) for i, path in enumerate(paths): print "working on [%d]" % i, path if basename(path) in excludeList: print "excluded (to be tested later)" continue # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: renderPM.drawToFile(drawing, base, 'PNG') except: print "could not save as PNG [%d]" % i, path
def export_save(request): svg = request.POST.get("svg_xml") title = request.POST.get("title") format = request.POST.get("format") country = request.POST.get("country") year = request.POST.get("year") viz = request.POST.get("viz") # import os directory = "exports/%s" % viz if not os.path.exists(directory): os.makedirs(directory) directory = "exports/%s/%s" % (viz, country) if not os.path.exists(directory): os.makedirs(directory) file_name = '/%s.%s' % (title, format) file_name = directory + file_name if format == "svg": # Set mimetype to octet-stream to assure download from browser svg = svg.encode( "utf-8" ) f = open(file_name, 'w') f.write(svg) elif format == "pdf": doc = xml.dom.minidom.parseString(svg.encode( "utf-8" )) svg = doc.documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() renderPDF.drawToFile(drawing, file_name) # # pdf = renderPDF.drawToString(drawing) # # response = HttpResponse(mimetype='application/pdf') # response.write(pdf) # Need to change with actual title return HttpResponse(title)
def demo(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) renderPDF.drawToFile(drawing, 'example1.pdf', 'My First Drawing') return drawing
data = [] for line in open("Predict.txt", "r").readlines(): # line = line.decode() if not line.isspace() and line[0] not in COMMENT_CHARS: data.append([float(n) for n in line.split()]) pred = [row[2] for row in data] high = [row[3] for row in data] low = [row[4] for row in data] times = [row[0] + row[1] / 12.0 for row in data] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [ list(zip(times, pred)), list(zip(times, high)), list(zip(times, low)) ] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green drawing.add(lp) drawing.add(String(250, 150, "Sunspots", fontSize=14, fillColor=colors.red)) renderPDF.drawToFile(drawing, "report2.pdf", "Sunspots")
from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF s = String(50, 50, 'Hello World', textAnchor='middle') d = Drawing(100, 100) d.add(s) renderPDF.drawToFile(d, 'hello.pdf', 'a simple pdf file')
def test2(self): "Generate PDF and SVG documents of third sample drawing." d = self.makeDrawing2() renderPDF.drawToFile(d, outputfile('test_widgets_grids2.pdf')) renderSVG.drawToFile(d, outputfile('test_widgets_grids2.svg'))
high = [row[3] for row in data] #第三列的数据作为最高值 low = [row[4] for row in data] #第四列的数据作为最低值 times = [row[0] + row[1] / 12.0 for row in data] #第一列的数据作为横坐标的时间 lp = LinePlot() #这里的x,y lp这个图像在我们drawing里面的起点坐标 lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 #下面里面的zip里面的数据显示在图标上。第一个是年份,第二个是数据量 lp.data = [ zip(times, pred), zip(times, high), zip(times, low), zip(times, addOne) ] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green lp.lines[3].strokeColor = colors.black #这里就是画图,画到drawing上面去 drawing.add(lp) drawing.add(String(250, 150, 'Sunspots', fontSize=14, fillColor=colors.red)) renderPDF.drawToFile(drawing, 'Graph.pdf', 'SunSpots')
from reportlab.lib.pagesizes import A4 guion = [] imagen = Image( 400, 10, 596, 133, "/home/local/DANIELCASTELAO/fsancheztemprano/Imágenes/triforce.jpg") dibujo = Drawing(30, 30) dibujo.add(imagen) dibujo.translate(0, 600) guion.append(dibujo) dibujo = Drawing(30, 30) dibujo.add(imagen) dibujo.rotate(45) dibujo.scale(1.5, 0.5) dibujo.translate(-90, 300) guion.append(dibujo) dibujo = Drawing(30, 30) dibujo.add(imagen) dibujo.rotate(90) dibujo.translate(-20, -100) guion.append(dibujo) dibujo = Drawing(A4[0], A4[1]) for deb in guion: dibujo.add(deb) renderPDF.drawToFile(dibujo, "prueba2.pdf")
def test(): """This function produces a pdf with examples of all the signs and symbols from this file. """ labelFontSize = 10 D = shapes.Drawing(450,650) cb = Crossbox() cb.x = 20 cb.y = 530 D.add(cb) D.add(shapes.String(cb.x+(cb.size/2),(cb.y-(1.2*labelFontSize)), cb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) tb = Tickbox() tb.x = 170 tb.y = 530 D.add(tb) D.add(shapes.String(tb.x+(tb.size/2),(tb.y-(1.2*labelFontSize)), tb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) yn = YesNo() yn.x = 320 yn.y = 530 D.add(yn) tempstring = yn.__class__.__name__ + '*' D.add(shapes.String(yn.x+(tb.size/2),(yn.y-(1.2*labelFontSize)), tempstring, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(130,6, "(The 'YesNo' widget returns a tickbox if testvalue=1, and a crossbox if testvalue=0)", fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize*0.75)) ss = StopSign() ss.x = 20 ss.y = 400 D.add(ss) D.add(shapes.String(ss.x+(ss.size/2), ss.y-(1.2*labelFontSize), ss.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ne = NoEntry() ne.x = 170 ne.y = 400 D.add(ne) D.add(shapes.String(ne.x+(ne.size/2),(ne.y-(1.2*labelFontSize)), ne.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) sf = SmileyFace() sf.x = 320 sf.y = 400 D.add(sf) D.add(shapes.String(sf.x+(sf.size/2),(sf.y-(1.2*labelFontSize)), sf.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ds = DangerSign() ds.x = 20 ds.y = 270 D.add(ds) D.add(shapes.String(ds.x+(ds.size/2),(ds.y-(1.2*labelFontSize)), ds.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) na = NotAllowed() na.x = 170 na.y = 270 D.add(na) D.add(shapes.String(na.x+(na.size/2),(na.y-(1.2*labelFontSize)), na.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ns = NoSmoking() ns.x = 320 ns.y = 270 D.add(ns) D.add(shapes.String(ns.x+(ns.size/2),(ns.y-(1.2*labelFontSize)), ns.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a1 = ArrowOne() a1.x = 20 a1.y = 140 D.add(a1) D.add(shapes.String(a1.x+(a1.size/2),(a1.y-(1.2*labelFontSize)), a1.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a2 = ArrowTwo() a2.x = 170 a2.y = 140 D.add(a2) D.add(shapes.String(a2.x+(a2.size/2),(a2.y-(1.2*labelFontSize)), a2.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) fd = FloppyDisk() fd.x = 320 fd.y = 140 D.add(fd) D.add(shapes.String(fd.x+(fd.size/2),(fd.y-(1.2*labelFontSize)), fd.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) renderPDF.drawToFile(D, 'signsandsymbols.pdf', 'signsandsymbols.py') print 'wrote file: signsandsymbols.pdf'
bc.y = 75 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 7000000 bc.valueAxis.valueMax = 23000000 bc.valueAxis.valueStep = 1000000 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(set(car_name_lst[:10])) d.add(bc) renderPDF.drawToFile(d, 'example2.pdf', 'My 2nd Drawing') #lab = Label() #lab.setOrigin(100,90) #lab.boxAnchor = 'ne' #lab.angle = 45 #lab.dx = 0 #lab.dy = -20 #lab.boxStrokeColor = colors.green #lab.setText('Some Multi-Line Label') #d.add(lab) #data = [(0, 45)] #xAxis = XValueAxis() #xAxis.setPosition(15, 150, 180) #xAxis.valueSteps = [10, 15, 20, 30, 35, 40]
from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF d = Drawing(100, 100) s = String(50, 50, "Hello, World!", textAnchor="middle") d.add(s) renderPDF.drawToFile(d, "hello.pdf", "A simple PDF file")
# 绘制折线 其实就是使用对象PolyLine 这个类来绘制折线 from reportlab.graphics.shapes import Drawing, PolyLine from reportlab.graphics import renderPDF d = Drawing(400, 400) # 通过点生成需要绘制的线。 里面的都是点 坐标的方向是 竖直y 向上越大 水平x 向右越大 lines = PolyLine([(100, 100), (200, 0), (200, 200)]) d.add(lines) renderPDF.drawToFile(d, "line4.pdf", " line file")
while True: try: filename = str(num) url = imagePrefix + filename r = requests.get(url, stream=True) r.raise_for_status() except HTTPError: pdfOutputFile.close() get_ipython().system('rm temp.pdf') print('Stopping') break else: r.raw.decode_content = True drawing = svg2rlg(r.raw) renderPDF.drawToFile(drawing, 'temp.pdf') # compressPDF('temp.pdf') pdfPage = open('temp.pdf', 'rb') # open in read mode pdfReader = PyPDF2.PdfFileReader(pdfPage) for pageNum in range(pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) pdfWriter.addPage(pageObj) pdfWriter.write(pdfOutputFile) pdfPage.close() print('Downloaded slide ', num) num += 1 #################################### print("Pdf is up!!")
from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF drawing = svg2rlg("Freesample.svg") renderPDF.drawToFile(drawing, "svg2pdf.pdf")
#!/usr/bin/env python # -*- coding:utf-8 -*- from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF d = Drawing(100, 100) s = String(50, 50, "hello world", textAnchor='middle') d.add(s) renderPDF.drawToFile(d, 'hello0.pdf', 'A simple pdf file', autoSize=0) renderPDF.drawToFile(d, 'hello1.pdf', 'A simple pdf file', autoSize=1)
def test1(self): "Generate PDF and SVG documents of second sample drawing." d = self.makeDrawing1() renderPDF.drawToFile(d, outputfile('test_widgets_grids1.pdf')) renderSVG.drawToFile(d, outputfile('test_widgets_grids1.svg'))
, (2007,11, 109.8, 116.8, 102.8) , (2007,12,107.3, 115.3, 99.3) , (2008,1 , 105.2, 114.2, 96.2) , (2008,2, 104.1, 114.1, 94.1) , (2008,3, 99.9, 110.9, 88.9) , (2008,4,94.8, 106.9, 82.8) , (2008,5, 91.2, 104.2, 78.2) ] #设定画布的宽高 drawing = Drawing(200,150) #求取的是:data里面的 第三项 - 40 做成的一个集合 pred = [row[2]- 40 for row in data] height = [row[3]- 40 for row in data] low = [row[4] - 40 for row in data] times = [200*((row[0]+ row[1]/12.0) - 2007)-110 for row in data] drawing.add(PolyLine( list( zip(times,pred) ) , strokeColor=colors.blue)); drawing.add(PolyLine(list( zip(times,low) ),strokeColor=colors.red)); drawing.add(PolyLine( list(zip(times,height) ),strokeColor=colors.green)); renderPDF.drawToFile(drawing,"report4.pdf","sun_hei_line")
#ファイル名Chapter21/polyline.py from reportlab.graphics.shapes import Drawing, String, PolyLine from reportlab.graphics import renderPDF # d = Drawing(300, 300) # p = PolyLine([(0, 0), (100, 100), (100, 0), (0, 100)]) # d.add(p) # renderPDF.drawToFile(d, 'polyline.pdf', 'polyline pdf file') d = Drawing(200, 200) p = PolyLine([(50, 50), (150, 150), (150, 50), (50, 150)]) d.add(p) renderPDF.drawToFile(d, 'polyline.pdf', 'polyline pdf file')
# -*- coding:utf-8 -*- # 用reportLab画图 from reportlab.lib import colors from reportlab.graphics.shapes import * from reportlab.graphics import renderPDF d = Drawing(100.100) # 创建指定大小的图纸 s = String(50, 50, 'Hello,Word!', textAnchor='middle') # 创建图形元素 d.add(s) renderPDF.drawToFile(d, 'hello.pdf', 'A simple PDF file') #将元素添加到图纸中去 # 构造折线 # reportLab针对这个需求有特定的类:PolyLine,它把坐标列表作为第一个参数。列表形式是[(x0,y0),(x1,y1),(x2,y2),....] # 编写原型 # 构造数据源 data = [ #Year month pred high low (2007, 8, 113.2, 114.2, 112.2), (2007, 9, 112.8, 115.8, 109.8), (2007, 10, 111.0, 116.0, 106.0), (2007, 11, 109.8, 116.8, 102.8), (2007, 12, 107.3, 115.5, 99.3), (2008, 1, 105.2, 114.2, 96.2), (2008, 2, 104.1, 114.1, 94.1), (2008, 3, 99.9, 110.9, 88.9), (2008, 4, 94.8, 106.8, 82.8), (2008, 5, 91.2, 104.2, 78.2) ] drawing = Drawing(200, 150) pred = [row[2] - 40 for row in data] high = [row[3] - 40 for row in data]
def startAnalyze(self): global gasin asin = str(gasin.get()) root.destroy() start_time = time.time() u1 = 'https://www.amazon.in/product-reviews/' u2 = u1 + asin para = '?sortBy=recent&reviewerType=all_reviews' u3 = u2 + para amazon_url = u3 user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' headers = {'User-Agent': user_agent} try: page = requests.get(amazon_url, headers=headers) except: print("Some error has occured!") try: parser = html.fromstring(page.content) except: parser = html.fromstring(page.content) xpath_but = '//*[@id="cm_cr-pagination_bar"]/ul/li[7]/a/text()' xpath_reviews = '//div[@data-hook="review"]' xpath_title = './/a[@data-hook="review-title"]//text()' xpath_prod_name = '//*[@id="cm_cr-product_info"]/div/div[2]/div/div/div[2]/div[1]/h1/a/text()' xpath_body = './/span[@data-hook="review-body"]//text()' but = parser.xpath(xpath_but) reviews = parser.xpath(xpath_reviews) if len(but) is not 0: r = int(but[0].replace(',', '')) + 1 else: if len(reviews) is not 0: r = 2 else: print("No review available for this product!") sys.exit() name = parser.xpath(xpath_prod_name) try: tt = name[0] except IndexError: raise Exception("Invalid Product Id") print(name[0]) tt = re.sub('[\\/:"*?<>|$]+', '', name[0]) print("Total no of pages.") print(r - 1) print( "Now we can estimate the required time! It depends on your network..." ) print("The counting will go upto the total number of pages...") temp = amazon_url + '&pageNumber=' pos = 0 neg = 0 sid = SentimentIntensityAnalyzer() ind = "compound" rc = 0 for i in range(1, r): a_url = temp + str(i) print(i) try: page = requests.get(a_url, headers=headers, timeout=60) except: page = requests.get(a_url, headers=headers, timeout=120) parser = html.fromstring(page.content) reviews = parser.xpath(xpath_reviews) for review in reviews: title = review.xpath(xpath_title) body = review.xpath(xpath_body) rc += 1 if len(body) is not 0: d = title[0] + ' ' ss = sid.polarity_scores(d + body[0]) k = ss[ind] if (k > 0): pos += 1 pr = str(format((pos / rc) * 100, '.3f')) + "%" print("Positive: ") print(pr) print("Total reviews: ") print(rc) print("%s time in seconds" % (time.time() - start_time)) neg = rc - pos if len(tt) > 255: tt = tt[:255] d = Drawing(21 * cm, 29.7 * cm) pc = Pie() pc.x = 200 pc.y = 150 pc.width = 220 pc.height = 220 pc.data = [pos, neg] pc.labels = ['Positive', 'Negative'] pc.slices.strokeWidth = 0.5 pc.slices[1].popout = 6 d.add(pc) fon = 22 d.add(String(14, 670, 'Product Name: ' + tt[:42], fontSize=fon)) count = int(len(tt) / 41) - 1 if (len(tt) % 41 != 0): count += 1 for i in range(1, count + 1): d.add( String(14, 670 - i * 30, ' ' + tt[(42 * i):(42 * i + 42)], fontSize=fon)) d.add( String( 14, 640 - count * 30, 'Product Id: ' + asin, fontSize=fon, )) d.add( String(14, 610 - count * 30, 'Total number of reviews: ' + str(rc), fontSize=fon)) d.add( String(14, 580 - count * 30, 'Number of Positive Reviews: ' + str(pos), fontSize=fon)) d.add( String(14, 550 - count * 30, 'Number of Negative Reviews: ' + str(neg), fontSize=fon)) d.add(String(14, 520 - count * 30, 'Rating: ' + pr, fontSize=fon)) renderPDF.drawToFile(d, tt + '.pdf', ' Review Report')
sp.labels = ['U', 'V', 'W', 'X', 'Y', 'Z'] sp.strands.strokeWidth = 1 sp.strands[0].fillColor = colors.pink sp.strands[1].fillColor = colors.lightblue sp.strands[2].fillColor = colors.palegreen sp.strands[0].strokeColor = colors.red sp.strands[1].strokeColor = colors.blue sp.strands[2].strokeColor = colors.green sp.strands.symbol = "FilledDiamond" sp.strands[1].symbol = makeMarker("Circle") sp.strands[1].symbol.strokeWidth = 0.5 sp.strands[1].symbol.fillColor = colors.yellow sp.strands.symbolSize = 6 sp.strandLabels[0, 3]._text = 'special' sp.strandLabels[0, 1]._text = 'one' sp.strandLabels[0, 0]._text = 'zero' sp.strandLabels[1, 0]._text = 'Earth' sp.strandLabels[2, 2]._text = 'Mars' sp.strandLabels.format = 'values' sp.strandLabels.dR = -5 d.add(sp) return d if __name__ == '__main__': d = sample1() from reportlab.graphics.renderPDF import drawToFile drawToFile(d, 'spider.pdf') d = sample2() drawToFile(d, 'spider2.pdf')
# coding=utf-8 from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF d = Drawing(100, 100) # 创建一个自动尺寸的Drawing对象 s = String(x=50, y=50, text='Hello, world!', textAnchor='middle') # 创建指定属性的图形元素 d.add(s) # 添加图形元素到Drawing对象 renderPDF.drawToFile(d, 'hello.pdf', 'A simple PDF file') # 以PDF格式渲染Drawing对象,并将结果保存到文件 # ### ReportLab # HomePage: https://www.reportlab.com/ # Documentation: https://www.reportlab.com/documentation/ # 可以创建多种格式的图表文档,功能强大易于使用;
def test0(self): "Generate PDF and SVG documents of first sample drawing." d = self.makeDrawing0() renderPDF.drawToFile(d, outputfile('test_widgets_grids0.pdf')) renderSVG.drawToFile(d, outputfile('test_widgets_grids0.svg'))
from reportlab.graphics import renderPDF from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont '''--- 添加中文支持 ---''' # pdfmetrics.registerFont(TTFont('msyh', 'msyh.ttf')) # 注册要使用的字体 # pdfmetrics.registerFont(TTFont('g', 'futurama.ttf')) pdfmetrics.registerFont(TTFont('song', 'SimSun.ttf')) #注册字体 STHeiti Medium.ttc '''--- 创建画布 ---''' d = Drawing(300, 200) # 创建画布并设置画布尺寸 '''--- 创建文本内容并设置样式与位置 ---''' s1 = String(150, 100, '这是中文文字测试') # 创建字符串并设置坐标、内容 s1.fontName = 'song' # 设置字体 s1.fontSize = 14 # 设置字号 s1.fillColor = colors.red # 设置字体颜色 s1.textAnchor = 'middle' # 设置锚点为中心(即位置坐标为文本中心点坐标) s2 = String(150, 120, '汉子!', fontName='song', fontSize=16, fillColor=colors.red, textAnchor='middle') # 另一种设置方式 '''--- 添加内容到画布并生成PDF文件 ---''' d.add(s1) # 将字符串添加到画布 d.add(s2) renderPDF.drawToFile(d, 'myPDF.pdf', '231231') # 生成PDF文件并设置文件名称与文档描述
from reportlab.graphics.shapes import Drawing, String, PolyLine from reportlab.graphics import renderPDF d = Drawing(100,100) s = String(50, 50, 'hello, world', textAnchor = 'middle') d.add(s) renderPDF.drawToFile(d, 'hello.pdf', 'A simple PDF file')
return d def sample4(): "Make a more complex demo with Label Overlap fixing" d = Drawing(400, 400) dn = Doughnut() dn.x = 50 dn.y = 50 dn.width = 300 dn.height = 300 dn.data = [[10, 20, 30, 40, 50, 60], [10, 20, 30, 40]] dn.labels = ['a', 'b', 'c', 'd', 'e', 'f'] dn.checkLabelOverlap = True d.add(dn) return d if __name__ == '__main__': from reportlab.graphics.renderPDF import drawToFile d = sample1() drawToFile(d, 'doughnut1.pdf') d = sample2() drawToFile(d, 'doughnut2.pdf') d = sample3() drawToFile(d, 'doughnut3.pdf')
from reportlab.graphics.shapes import * from reportlab.graphics import renderPDF data = [ # Year Month Predicted High Low (2007, 8, 113.2, 114.2, 112.2), (2007, 9, 112.8, 115.8, 109.8), (2007, 10, 111.0, 116.0, 106.0), (2007, 11, 109.8, 116.8, 102.8), (2007, 12, 107.3, 115.3, 99.3), (2008, 1, 105.2, 114.2, 96.2), (2008, 2, 104.1, 114.1, 94.1), (2008, 3, 99.9, 110.9, 88.9), (2008, 4, 94.8, 106.8, 82.8), (2008, 5, 91.2, 104.2, 78.2), ] drawing = Drawing(200, 200) pred = [row[2] - 40 for row in data] high = [row[3] - 40 for row in data] low = [row[4] - 40 for row in data] times = [200 * ((row[0] + row[1] / 12.0) - 2007) - 110 for row in data] drawing.add(PolyLine(zip(times, pred), strokeColor=colors.blue)) drawing.add(PolyLine(zip(times, high), strokeColor=colors.red)) drawing.add(PolyLine(zip(times, low), strokeColor=colors.green)) drawing.add(String(65, 115, 'Sunspots', fontSize=16, fillColor=colors.red)) renderPDF.drawToFile(drawing, 'chart1.pdf', 'Sunspots')
#!/usr/bin/python import cgi, sys from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF form = cgi.FieldStorage() xml_value = form.getvalue("xml2") svg_file = open("/var/www/html/tmp/oncoprint_converter.svg", "w") svg_file.write(xml_value) svg_file.close() print 'Content-Disposition: attachment; filename="oncoprint.pdf"\r\n\r\n'; #print 'Content-Type: application/pdf \r\n\r\n'; drawing = svg2rlg("/var/www/html/tmp/oncoprint_converter.svg") renderPDF.drawToFile(drawing, "/var/www/html/tmp/oncoprint_converter.pdf") download_file = open("/var/www/html/tmp/oncoprint_converter.pdf", "r").read() print download_file download_file.flush() download_file.close()
from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF, renderPM drawing = svg2rlg("poster_test_1.svg") renderPDF.drawToFile(drawing, "file2.pdf") renderPM.drawToFile(drawing, "file2.png", fmt="PNG")
URL = 'http://www.swpc.noaa.gov/ftpdir/weekly/Predict.txt' COMMENT_CHARS = '#:' drawing = Drawing(400, 200) data = [] for line in urlopen(URL).readlines(): if not line.isspace() and not line[0] in COMMENT_CHARS: data.append([float(n) for n in line.split()]) pred = [row[2] for row in data] high = [row[3] for row in data] low = [row[4] for row in data] times = [row[0] + row[1] / 12.0 for row in data] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [zip(times, pred), zip(times, high), zip(times, low)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green drawing.add(lp) drawing.add(String(250, 150, 'Sunspots', fontSize=14, fillColor=colors.red)) renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots')
from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF, renderPM import sys import os args = sys.argv filename = args[1] filename_without_ext = os.path.splitext(os.path.basename(filename))[0] drawing = svg2rlg(filename) renderPDF.drawToFile(drawing, filename_without_ext + ".pdf") drawing = svg2rlg(filename) renderPM.drawToFile(drawing, filename_without_ext + ".png", fmt="PNG")
def svgToPdf(name, link): open(name + ".svg", "wb").write(get(link).content) renderPDF.drawToFile(svg2rlg(name + ".svg"), name + ".pdf") os.remove(name + ".svg")
from reportlab.graphics.shapes import Image, Drawing from reportlab.graphics import renderPDF from reportlab.lib.pagesizes import A4 imaxes = [] imaxe = Image(0, 0, 500, 102, "/home/manuel/Descargas/logoCole.jpg") debuxo = Drawing(500, 102) debuxo.translate(0, 700) debuxo.add(imaxe) imaxes.append(debuxo) debuxo2 = Drawing(250, 51) debuxo2.add(imaxe) debuxo2.rotate(45) debuxo2.translate(500, 50) debuxo2.scale(0.5, 1.5) imaxes.append(debuxo2) documento = Drawing(A4[0], A4[1]) for elemento in imaxes: documento.add(elemento) renderPDF.drawToFile(documento, "segundoInforme.pdf")