def f(xml_path): """ This function process SVG files based on the path to XML file. This function produces a single PDF file as a result. """ filename = os.path.splitext(os.path.basename(xml_path))[0] svg_paths = glob.glob('svg/{:}*.svg'.format(filename)) # Sort by pages svg_paths = sorted(svg_paths, key=lambda x: int(x.replace('.', '-').split('-')[1])) # Individually convert SVG to PDF for idx, svg_path in enumerate(svg_paths): svg2pdf(url=svg_path, write_to='pdf/{:}-{:}.pdf'.format(filename, idx)) # Merge pdf merger = PdfFileMerger() for idx, svg_path in enumerate(svg_paths): merger.append('pdf/{:}-{:}.pdf'.format(filename, idx)) # Write PDF merger.write('pdf/{:}.pdf'.format(filename)) # Remove tmp pdf files for idx, svg_path in enumerate(svg_paths): os.remove('pdf/{:}-{:}.pdf'.format(filename, idx))
def render_wavedrom_cli(sphinx, node, outpath, bname, image_format): '''Function for generating the image using the wavedrom-cli executable Args: sphinx (sphinx): Sphinx instance node (wavedromnode): The wavedrom node containing the wavedrom json content outpath (str): The path where the (temporary) output should be written bname (str): The filename (without full path) to be used for the file generation image_format (str): The desired image format. Possible options are: - "image/svg+xml" - "application/pdf" - "image/png" Returns: str: The filename (without full path) of the generated image output Raises: OSError: File not found SphinxError: OSError during execution of the wavedrom command SphinxError: Non-zero return code SphinxError: Invalid image format input string ''' fname = None ensuredir(outpath) input_json = os.path.join(outpath, "{}.{}".format(bname, 'json5')) output_svg = os.path.join(outpath, "{}.{}".format(bname, 'svg')) with open(input_json, 'w') as input_json_file: input_json_file.write(node['code']) try: process = subprocess.run(generate_wavedrom_args( sphinx, input_json, output_svg), stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) except OSError as err: if err.errno != ENOENT: raise raise SphinxError('wavedrom command %r cannot be run' % sphinx.builder.config.wavedrom_cli) if process.returncode != 0: raise SphinxError('error while running wavedrom\n\n%s' % process.stderr) # SVG can be directly written and is supported on all versions if image_format == 'image/svg+xml': fname = "{}.{}".format(bname, "svg") elif image_format == 'application/pdf': fname = "{}.{}".format(bname, "pdf") fpath = os.path.join(outpath, fname) cairosvg.svg2pdf(url=output_svg, write_to=fpath) elif image_format == 'image/png': fname = "{}.{}".format(bname, "png") fpath = os.path.join(outpath, fname) cairosvg.svg2png(url=output_svg, write_to=fpath) else: raise SphinxError('Invalid choice of image format: \n\n%s' % image_format) return fname
def render_wavedrom_py(node, outpath, bname, image_format): """ Render a wavedrom image """ # Try to convert node, raise error with code on failure try: svgout = render(node["code"]) except JSONDecodeError as exception: raise SphinxError( "Cannot render the following json code: \n{} \n\nError: {}".format( node['code'], exception)) if not os.path.exists(outpath): os.makedirs(outpath) # SVG can be directly written and is supported on all versions if image_format == 'image/svg+xml': fname = "{}.{}".format(bname, "svg") fpath = os.path.join(outpath, fname) svgout.saveas(fpath) return fname if image_format == 'application/pdf': fname = "{}.{}".format(bname, "pdf") fpath = os.path.join(outpath, fname) cairosvg.svg2pdf(svgout.tostring(), write_to=fpath) return fname if image_format == 'image/png': fname = "{}.{}".format(bname, "png") fpath = os.path.join(outpath, fname) cairosvg.svg2png(svgout.tostring(), write_to=fpath) return fname raise SphinxError("No valid wavedrom conversion supplied")
def exportsvg(fromDir, targetDir, exportType): print( "开始执行转换命令...") num = 0 for a,f,c in os.walk(fromDir):#使用walk遍历源目录 for fileName in c: path = os.path.join(a,fileName)#获得文件路径 if os.path.isfile(path) and fileName[-3:] == "svg":#判断文件是否为svg类型 num += 1 fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(targetDir, fileName[:-3] + exportType)#生成目标文件路径 exportFileHandle = open(exportPath,'w') if exportType == "png": try: cairosvg.svg2png(bytestring=svg, write_to=exportPath)#转换为png文件 except: print( "error in convert svg file : %s to png."%(path)) elif exportType == "pdf": try: cairosvg.svg2pdf(bytestring=svg, write_to=exportPath)#转换为pdf文件 except: print( "error in convert svg file: %s to pdf."%(path)) exportFileHandle.close() print("Success Export ", exportType, " -> " , exportPath) print("已导出 ", num, "个文件")#统计转换文件数量
def render_nlpgraphics(renderer, filtered, filepath: str = None, output_type: str = 'SVG'): """Render an NLPInstance into the supported formats. Args: renderer (SingleSentenceRenderer or AlignmentRenderer): The renderer object. filtered (NLPInstance): The filtered NLPInstane to be rendered. filepath (str): The path of the outputfile. output_type (str): The type of the output format. Returns: The bytesting of the rendered object if needed. """ svg_scene = Drawing(size=('100%', '100%')) # default: '100%', '100%' dim = renderer.render(filtered, svg_scene) # Set the actual computed dimension without rerendering svg_scene.attribs['width'] = dim[0] svg_scene.attribs['height'] = dim[1] svg_bytes = svg_scene.tostring().encode('UTF-8') if filepath is not None and output_type == 'SVG': svg_scene.saveas(filepath) elif filepath is None and output_type == 'SVG': return svg_bytes elif output_type == 'PS': cairosvg.svg2ps(bytestring=svg_bytes, write_to=filepath) elif output_type == 'PDF': cairosvg.svg2pdf(bytestring=svg_bytes, write_to=filepath) else: raise ValueError( '{0} not a supported filetype!'.format(output_type))
def main(color, design, eyes, eye_color, file_type, file_name, value, logo, grid): """The main application program.""" if grid: final_svg = make_grid(color, design, eyes, eye_color, file_type, logo, grid) else: final_svg = make_one_qr_svg(color, design, eyes, eye_color, file_type, value, logo, grid, errcorlvl=QrCode.Ecc.MEDIUM) if file_type == 'pdf': cairosvg.svg2pdf(bytestring=final_svg, write_to=file_name + ".pdf") if file_type == 'png': cairosvg.svg2png(bytestring=final_svg, write_to=file_name + ".png") if file_type == 'svg': with open(file_name + ".svg", "w") as text_file: print(final_svg, file=text_file)
def exportsvg(inputDir, exportType, outputDir): if not os.path.exists(outputDir): os.mkdir(outputDir) num = 0 for a,f,c in os.walk(inputDir): for fileName in c: path = os.path.join(a, fileName) if os.path.isfile(path) and fileName.endswith('.svg'): num += 1 fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(outputDir, fileName[:-3] + exportType) exportFileHandle = open(exportPath, 'w') if exportType == "png": try: cairosvg.svg2png(bytestring=svg, write_to=exportPath) except: print "error in convert svg file : %s to png."%(path) elif exportType == "pdf": try: cairosvg.svg2pdf(bytestring=svg, write_to=exportPath) except: print "error in convert svg file: %s to pdf."%(path) exportFileHandle.close() print "Success Export ", exportType, " -> ", exportPath print num, " files are tranformed from svg to ", exportType
def main(coupon): coupon = coupon.upper() # Generate QR code. url = 'https://selectel.ru?utm_source=github.com' \ '&utm_medium=pdf_create_from_svg&utm_campaign=coupon' \ f'&coupon={coupon}' qr_svg = _create_qr_code(url) # Generate coupon. coupon_svg = svg_template.render(name=coupon, qr_code=qr_svg, discount="-30%") coupon_pdf = BytesIO() cairosvg.svg2pdf(bytestring=bytearray(coupon_svg.encode("utf-8")), write_to=coupon_pdf, scale=2) # Upload new image. coupon_pdf.seek(0) file_name = f"coupon-{coupon}.pdf" storage.put_object(COUPONS_CONTAINER, file_name, coupon_pdf) # Close streams. coupon_pdf.close() return file_name
def svg42pdf_cairo(svg_fn, pdf_fn): import cairosvg cairosvg.svg2pdf( file_obj=open(svg_fn, "rb"), write_to=pdf_fn, ) report(svg_fn, pdf_fn)
def getPDFs(dpath,sub, fpath): #data/fmriprep/ses-1/sub-001/fmriprep/sub-001 #Experiments/EricData/data/fmriprep/sub-001/ses-1/fmriprep/sub-001/figures svgs= glob.glob(os.path.join(fpath, sub, 'ses-1', 'fmriprep', sub, 'figures', '*rois.svg')) for img in svgs: print('>>>>>SVG IMG: ', img) # get our current filename name = img.split('/') for word in name: if '.svg' in word: word = word.split('.')[0] filename=word+'.png' out=os.path.join(dpath, 'test', filename) #output pdf filename print(" %s ------> %s "%(img, out)) cairosvg.svg2png(url=img, write_to=out) #convert svg if not os.path.exists(out): cairosvg.svg2pdf(url=img, write_to=out) #convert svg packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=letter) can.drawString(10, 100, "W") can.save() packet.seek(0) new_pdf = PdfFileReader(packet) existing_pdf = PdfFileReader(open(out, "rb")) output = PdfFileWriter() page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) outputStream = open("Test_"+filename, "wb") output.write(outputStream) outputStream.close()
def lang_prescription(doctor, file, lang, order_num): """ Create a pdf prescription notebooks for the corresponding doctor by language :param doctor: Dictionary :param file: Str (filename) :param lang: Str :param order_num: str :return: - """ doctor['image_bar_code'] = render(str(doctor['h_bar_code'])[:-1]) doctor['signet'] = signet_maker(doctor) with open(file, mode='r') as f: template = Template(f.read()) filled_template = template.substitute(doctor) with open("tmp_nb.svg", mode='w+') as f: f.write(filled_template) file_path = "notebooks/" + str(lang) + '.' + str(order_num) tmp = file_path i = 0 while os.path.exists(tmp + '.pdf'): tmp = file_path + '_' + str(i) i += 1 cairosvg.svg2pdf(url='tmp_nb.svg', write_to=tmp + '.pdf', dpi=72) os.remove('tmp_nb.svg')
def convert(self) -> None: if self.out_ext in self.multipage_formats: convert_out_dir = self.tempdir self.single_pages += [ convert_out_dir / self.page_filename.with_suffix(self.out_ext) ] else: convert_out_dir = self.export_filename.parent logger.info( "Converting file to '%s'", convert_out_dir / self.page_filename.with_suffix(self.out_ext), ) try: if self.out_ext == ".pdf": cairosvg.svg2pdf( url=str(self.svg_out_dir / self.page_filename.with_suffix(".svg")), write_to=str( convert_out_dir / self.page_filename.with_suffix(self.out_ext) ), ) elif self.out_ext == ".png": cairosvg.svg2png( url=str(self.svg_out_dir / self.page_filename.with_suffix(".svg")), write_to=str(convert_out_dir / self.page_filename), dpi=args.export_dpi, ) except urllib.error.URLError as exc: logger.error( "Missing linked image, export file might be missing: %s", exc.reason ) # TODO: Read filename
def pdf_cairo_export(name_out): #Cairo bug very often to translate svg to pdf.... import cairosvg bdir = os.path.dirname(name_out) try: os.mkdir(bdir+'/tmp') except: pass for islide in xrange(document._global_counter['slide']+1): print("Export slide %i"%islide) #check if content type need to be changed check_content_type_change( document._contents["slide_%i"%islide] ) tmp = render_slide( document._contents["slide_%i"%islide] ) try: cairosvg.svg2pdf(document._contents["slide_%i"%islide]['svg_output'], write_to = bdir+'/tmp/slide_%i.pdf'%islide) except: print("export failed") #join all pdf res = os.popen(pdfjoincmd+' %s*.pdf -o %s'%(bdir+'/tmp/',name_out)) output = res.read() res.close() msg = "Saved to %s"%name_out os.system('rm -rf %s'%(bdir+'/tmp')) return msg
def exportsvg(fromDir, targetDir, exportType): num = 0 for a,f,c in os.walk(fromDir):#使用walk遍历源目录 for fileName in c: path = os.path.join(a,fileName)#获得文件路径 if os.path.isfile(path) and fileName[-3:] == "svg":#判断文件是否为svg类型 num += 1 fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(targetDir, fileName[:-3] + exportType)#生成目标文件路径 exportFileHandle = open(exportPath,'w') if exportType == "png": try: cairosvg.svg2png(bytestring=svg, write_to=exportPath, scale = 40)#转换为png文件 if os.path.exists(path): os.remove(path) else: print("The file does not exist") except: print ("error in convert svg file : %s to png."%(path)) elif exportType == "pdf": try: cairosvg.svg2pdf(bytestring=svg, write_to=exportPath, scale = 40)#转换为pdf文件 except: print ("error in convert svg file: %s to pdf."%(path)) exportFileHandle.close()
def export_pdf(self, filename, width, height): cairosvg.svg2pdf( bytestring=self.svg.tostring(), write_to=filename, parent_width=width + (2 * self.margin), parent_height=height + (2 * self.margin), ) print(f"Rendered to {filename}")
def visualize_molecule(mol, filename="test_img"): global RDKIT_IMPORTED, SVG2PDF_IMPORTED if not RDKIT_IMPORTED: print("[!] WARNING: Skipped visualization of molecules as rdkit is not imported.") return tmp=AllChem.Compute2DCoords(mol) Draw.MolToFile(mol, filename+".svg", size=(400,400)) if SVG2PDF_IMPORTED: cairosvg.svg2pdf(url=filename+".svg", write_to=filename+".pdf")
def exportPDF(cls, filename): filepath, ext = os.path.splitext(filename) # TODO(sbauza): Modify that for knowing if it's a SVG file if ext != ".svg": # okay, it's not good to check the type by looking at the extension # but it's a quick workaround... raise Exception("%s is not a SVG file" % filename) dest = filepath + '.pdf' cairosvg.svg2pdf(url=filename, write_to=dest)
def genMarker(i, dicno, paper_size): print " Marker %d\r" % i, sys.stdout.flush() aruco_dict = aruco.Dictionary_get(dicno) img = aruco.drawMarker(aruco_dict, i, 2000) cv2.imwrite("/tmp/marker%d.png" % i, img) svg = genSvg(i, dicno, paper_size) cairosvg.svg2pdf(bytestring=svg, write_to='/tmp/marker%d.pdf' % i) os.remove("/tmp/marker%d.png" % i)
def save(self): # self.surface.write_to_svg() self.surface.finish() import cairosvg cairosvg.svg2pdf(url=self.output_fname_no_suffix + '.svg', write_to=self.output_fname_no_suffix + '.pdf') print( f"[Vangogh_Cairo.py] Cairo plot saved to {self.output_fname_no_suffix+'.svg/.pdf'}" )
def svg_to_pdf(svg, pdf): """Convert an SVG image to PDF. Args: svg (str): Input file - example.svg. pdf (str): Output file - example.pdf. """ svg2pdf(url=svg, write_to=pdf)
def output(self): self.dwg.filename = self.title + '.svg' print('Saved svg chessboard file:\n', self.dwg.filename, '') self.dwg.save() if self.pdf: cairosvg.svg2pdf(url=self.dwg.filename, write_to=self.title + '.pdf') print('Saved pdf chessboard file:\n', self.title + '.pdf', '')
def generate_letterpaper(letterpaper_dir, assets_dir, assets_config): """ This function generates the letterpaper from the assets. """ for n_asset, asset_config in enumerate( get_assets(assets_dir, assets_config)): filename = "letterpaper_{}".format(n_asset) svg_filename = "{}.svg".format(filename) pdf_filename = "{}.pdf".format(filename) png_filename = "{}.png".format(filename) thumb_filename = "{}_thumb.png".format(filename) svg_path = join(letterpaper_dir, svg_filename) pdf_path = join(letterpaper_dir, pdf_filename) png_path = join(letterpaper_dir, png_filename) thumb_path = join(letterpaper_dir, thumb_filename) print("Generating {} from {}".format(pdf_path, asset_config[FILENAME])) paper = svgwrite.Drawing(svg_path, size=("210mm", "297mm"), viewBox=("0 0 210 297")) # make bg white paper.add( paper.rect( insert=(0 * svgwrite.mm, 0 * svgwrite.mm), size=(210 * svgwrite.mm, 297 * svgwrite.mm), fill="white", )) # Add Pattern or Background image_path = join(assets_dir, asset_config[FILENAME]) image_dims = (asset_config[WIDTH], asset_config[HEIGHT]) if image_dims[0] > PAPER_WIDTH - PAPER_MARGIN: image_dims = tuple(image_dim / (image_dims[0] / (PAPER_WIDTH - PAPER_MARGIN)) for image_dim in image_dims) if image_dims[1] > PAPER_HEIGHT - PAPER_MARGIN: image_dims = tuple(image_dim / (image_dims[1] / (PAPER_HEIGHT - PAPER_MARGIN)) for image_dim in image_dims) image = svgimage( image_path, size=(image_dims), insert=(PAPER_MARGIN / 2, PAPER_MARGIN / 2), style=f"opacity:{asset_config[OPACITY]}", ) paper.add(image) # Save and Convert paper.save() cairosvg.svg2pdf(url=svg_path, write_to=pdf_path) cairosvg.svg2png(url=svg_path, write_to=png_path) cairosvg.svg2png(url=svg_path, write_to=thumb_path, scale=0.1)
def render(self, path, image_type): output = self.render_svg() if image_type == "PNG": svg2png(bytestring=output, write_to=path, scale=5) elif image_type == "PDF": svg2pdf(bytestring=output, write_to=path) elif image_type == "SVG": output = self.render_svg() with open(path, "w+") as target: target.write(output)
def plot_write(self, parsed_input): '''Write the plot to a file either as SVG or PDF.''' if parsed_input[0].split('.')[-1] == 'svg': self.plot.lighting_plot.write(os.path.expanduser(parsed_input[0])) elif parsed_input[0].split('.')[-1] == 'pdf': plot_bytes = ET.tostring(self.plot.lighting_plot.getroot()) cairosvg.svg2pdf(bytestring=plot_bytes, write_to=parsed_input[0]) else: print('WARNING: File format not supported, writing as SVG') self.plot.lighting_plot.write(os.path.expanduser(parsed_input[0]))
def convert(self, _from, _to): # type: (unicode, unicode) -> bool """Converts the image from SVG to PDF via CairoSVG.""" import cairosvg try: cairosvg.svg2pdf(url=_from, write_to=_to) except (OSError, URLError) as err: raise ExtensionError(__('CairoSVG converter failed with reason: ' '%s') % err.reason) return True
def convert_svg_2_pdf(svg_url, output_folder = None): try: if output_folder is None: cairosvg.svg2pdf(url = svg_url, write_to = svg_url[:-4] + ".pdf") else: if not os.path.exists(output_folder): os.makedirs(output_folder) cairosvg.svg2pdf(url = svg_url, write_to = os.path.join(output_folder, (svg_url.split("/")[-1][:-4] + ".pdf"))) except: print("{} threw an exception.".format(svg_url))
def convert_svg(svg_file_path, out_file_path, png_width=1000): import cairosvg filename, extension = path.splitext(out_file_path) if extension not in ['.pdf', '.eps', '.png']: raise ValueError('Invalid format. Use either .pdf, .eps, or .png') if extension == '.pdf': cairosvg.svg2pdf(url=svg_file_path, write_to=out_file_path) elif extension == '.eps': cairosvg.svg2ps(url=svg_file_path, write_to=out_file_path) elif extension == '.png': cairosvg.svg2png(url=svg_file_path, write_to=out_file_path, dpi=300)
def generate_pdfs(folder_path): svgs = [ file for file in os.listdir(folder_path) if file.endswith('.svg') ] for svg in svgs: svg_path = os.path.join(folder_path, svg) pdf_path = os.path.splitext(svg_path)[0] + '.pdf' try: svg2pdf(url=svg_path, write_to=pdf_path) except Exception: print('') print("done")
def convert(svg_file_path) -> None: pdf_file_path = svg_file_path[:-4] + '.pdf' if exists(path_join(self.document_dir, pdf_file_path)): source_mtime = stat(path_join(self.document_dir, svg_file_path)).st_mtime_ns target_mtime = stat(path_join(self.document_dir, pdf_file_path)).st_mtime_ns if source_mtime < target_mtime: print(f'File "{pdf_file_path}" is up to date.') return svg2pdf(url=path_join(self.document_dir, svg_file_path), write_to=path_join(self.document_dir, pdf_file_path))
def download_and_convert(url: str, i: int, out: str): try: wget.download('{}/svg/{}'.format(url, i), out='{}/{}/'.format(out, 'svg')) except urllib.error.HTTPError: return -1 print(' ' + str(i)) # Path to svg and pdf svg = '{}/{}/{}'.format(out, 'svg', i) pdf = '{}/{}/{}'.format(out, 'pdf', i) # Convert svg to pdf cairosvg.svg2pdf(url=svg, write_to=pdf) return 0
def create_multiple_sizes(file_name): name, ext = splitext(file_name) IMG_BASE_DIR = join(OUTPUT_BASE, name) os.makedirs(IMG_BASE_DIR) pdf_generated = False img_pdf_path = join(IMG_BASE_DIR, name + '_Global.pdf') if ext == '.xml': try: convertVd(file_name) except Exception as ex: return "Error during conversion to svg, {0}".format(str(ex)) convertVd(file_name) cairosvg.svg2png(url=name + '.xml.svg', write_to=name + '.png') file_name = name + '.png' if ext == '.svg': cairosvg.svg2png(url=file_name, write_to=name + '.png') cairosvg.svg2pdf(url=file_name, write_to=img_pdf_path) file_name = name + '.png' pdf_generated = True image = Image.open(file_name) name_3x = join(IMG_BASE_DIR, name + '_3x' + EXT_OUT) image.save(name_3x, 'PNG') if not pdf_generated: image_rgb = Image.new('RGB', image.size, (255, 255, 255)) image_rgb.paste(image, mask=image.split()[3]) image_rgb.save(img_pdf_path, 'PDF', resolution=100.0) # Get Images sizes width, height = image.size width_1x = int(width / 3) height_1x = int(height / 3) width_2x = int(width_1x * 2) height_2x = int(height_1x * 2) # Save with new sizes name_2x = join(IMG_BASE_DIR, name + '_2x' + EXT_OUT) img_2x = image.resize((width_2x, height_2x)) img_2x.save(name_2x, 'PNG') name_1x = join(IMG_BASE_DIR, name + '_1x' + EXT_OUT) img_1x = image.resize((width_1x, height_1x)) img_1x.save(name_1x, 'PNG') return name_1x, name_2x, name_3x, img_pdf_path
def getPDFs(dpath, sub, fpath): #data/fmriprep/ses-1/sub-001/fmriprep/sub-001 svgs = glob.glob( os.path.join(fpath, sub, 'fmriprep', sub, 'figures', '*flt_bbr.svg')) for img in svgs: # get our current filename name = img.split('/') for word in name: if '.svg' in word: word = word.split('.')[0] filename = word + '.pdf' out = os.path.join(dpath, sub, 'pdfs', filename) #output pdf filename cairosvg.svg2pdf(url=img, write_to=out) #convert svg #iterate through currently made images and write details to file pdfs = glob.glob(os.path.join(dpath, sub, 'pdfs', '*pdf')) for pdf in pdfs: name = pdf.split('/') for word in name: if '.pdf' in word: filename = word.split('.')[0] new_dest = os.path.join('derivatives', sub, 'pdfs', filename + "_01.pdf") packet = io.BytesIO() c = canvas.Canvas(packet) c.drawString(10, 100, "FILENAME: %s" % filename) c.save() pdf3 = os.path.join('derivatives', sub, 'pdfs', 'complete_pdfs', filename + ".pdf") packet.seek(0) pdf2 = PdfFileReader(packet) existing_pdf = PdfFileReader(open(pdf, 'rb')) output = PdfFileWriter() page = existing_pdf.getPage(0) page.mergePage(pdf2.getPage(0)) output.addPage(page) outputStream = open(pdf3, "wb") output.write(outputStream) outputStream.close()
def visit_bitfield_latex(self, node): from cairosvg import svg2pdf svg = jsonml_stringify( render( loads(' '.join(node.rawsource)), **node.options ) ) hashkey = str(node.options) + str(node.rawsource) fname = 'bitfield-{}.pdf'.format(sha1(hashkey.encode()).hexdigest()) outfn = join(self.builder.outdir, self.builder.imagedir, fname) svg2pdf(bytestring=svg, write_to=outfn) self.body.append(r'\sphinxincludegraphics[]{{{}}}'.format(fname))
def graph(self, save=''): """Finalize the graph and save if desired.""" self.t += '</svg>' if len(save) > 0: if save[-3:].lower() == 'png': cairosvg.svg2png(bytestring=self.t, write_to=save) elif save[-3:].lower() == 'pdf': cairosvg.svg2pdf(bytestring=self.t, write_to=save) elif save[-3:].lower() == 'svg': fp = open(save, 'w') fp.write(self.t) fp.close() else: return self.t
def _create_mentor_certificate(user, sc_slug, st_slug): icodes = user.created_codes.all() nschool = nstate = 0 awards = defaultdict(int) for icode in icodes: for attempt in Attempt.objects.filter(access_code=icode): if attempt.competition.slug == sc_slug: if list(attempt.confirmed_by.all()) != [user]: continue nschool += 1 elif attempt.competition.slug == st_slug: nstate += 1 else: continue for award in set(award.award.name for award in attempt.attemptaward_set.all()): awards[award] += 1 name = (user.first_name.strip() + u" " + user.last_name.strip()).title() text = _compose_text(name, nschool, awards) text = "\n".join(map(u'<tspan x="0" dy="1.2em">{}</tspan>'.format, text.splitlines())) cert_dir = os.path.join(settings.MEDIA_ROOT, _profile_file_path(user, "")) try: os.mkdir(cert_dir) except: pass template_file = os.path.join(AWARD_TEMPLATE_DIR, "certificate.svg") with open(template_file) as f: template = f.read() template = template.replace("ime_in_priimek", name.encode("utf-8")).replace("kategorija", text.encode("utf-8")) return cairosvg.svg2pdf(template)
def download(request): content = request.POST.get("file_content") title = request.POST.get("file_name").replace(" ", "_") file_format = request.POST.get("file_format").lower() valid_chars = string.ascii_letters + string.digits + "?_" title_clean = ''.join(ch for ch in title if ch in valid_chars) if len(content) == 0 or "</svg>" not in content: return HttpResponse(status=500, content="Invalid svg image.") if file_format == "svg": response = HttpResponse(content.encode("utf-8"), mimetype="application/octet-stream") elif file_format == "pdf": response = HttpResponse(cairosvg.svg2pdf(bytestring=content), mimetype="application/pdf") elif file_format == "png": response = HttpResponse(cairosvg.svg2png(bytestring=content), mimetype="image/png") else: return HttpResponse(status=500, content="Wrong image format.") response[ "Content-Disposition"] = "attachment; filename=%s.%s" % (title_clean, file_format) return response
def main(): parser = argparse.ArgumentParser(description="Convert and concatenate SVGs into PDF file") parser.add_argument("svg", nargs="+", help="list of svg files") parser.add_argument("--output", type=str, help='ouput PDF file (defaults to "output.pdf")') parser.set_defaults(output="output.pdf") args = parser.parse_args() merger = PdfFileMerger() print("Converting SVG into PDFs") for svg in args.svg: print(" - %s" % svg) pdffile = svg.replace(".svg", ".pdf") cairosvg.svg2pdf(bytestring=open(svg).read(), write_to=pdffile) merger.append(PdfFileReader(open(pdffile, "rb"))) print("Concatenating into PDF") merger.write(args.output)
def singlesvg2svg(fileName): fromDir = "source_data" targetDir = "." exportType = "png" path = os.path.join(fromDir,fileName) print path if os.path.isfile(path) and fileName[-3:] == "svg": fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(targetDir, fileName[:-3] + exportType) exportFileHandle = open(exportPath,'w') if exportType == "png": cairosvg.svg2png(bytestring=svg, write_to=exportPath) elif exportType == "pdf": cairosvg.svg2pdf(bytestring=svg, write_to=exportPath) exportFileHandle.close()
def view_ticket(request, event_slug): eventuser = EventUser.objects.filter(event__slug__iexact=event_slug).filter(user=request.user).first() if eventuser: ticket = generate_ticket(eventuser, request.META.get('LANG')) response = HttpResponse(cairosvg.svg2pdf(bytestring=ticket), content_type='application/pdf') response["Content-Disposition"] = 'filename=Ticket-' + str(eventuser.id).zfill(12) + '.pdf' return response else: messages.error(request, "You are not registered for this event") return HttpResponseRedirect(reverse("index", args=(event_slug,)))
def render_wavedrom(self, node, outpath, bname, format): """ Render a wavedrom image """ # Try to convert node, raise error with code on failure try: svgout = WaveDrom().renderWaveForm(0, json.loads(node['code'])) except JSONDecodeError as e: raise SphinxError("Cannot render the following json code: \n{} \n\nError: {}".format(node['code'], e)) if not os.path.exists(outpath): os.makedirs(outpath) # SVG can be directly written and is supported on all versions if format == 'image/svg+xml': fname = "{}.{}".format(bname, "svg") fpath = os.path.join(outpath, fname) svgout.saveas(fpath) return fname # It gets a bit ugly, if the output does not support svg. We use cairosvg, because it is the easiest # to use (no dependency on installed programs). But it only works for Python 3. try: import cairosvg except: raise SphinxError(__("Cannot import 'cairosvg'. In Python 2 wavedrom figures other than svg are " "not supported, in Python 3 ensure 'cairosvg' is installed.")) if format == 'application/pdf': fname = "{}.{}".format(bname, "pdf") fpath = os.path.join(outpath, fname) cairosvg.svg2pdf(svgout.tostring(), write_to=fpath) return fname if format == 'image/png': fname = "{}.{}".format(bname, "png") fpath = os.path.join(outpath, fname) cairosvg.svg2png(svgout.tostring(), write_to=fpath) return fname raise SphinxError("No valid wavedrom conversion supplied")
def saveImage(self, session_id, query_str, output_format, data): """ Serve image files for download. """ filename = ".".join((query_str, output_format)) filepath = os.path.join(cherrypy.session.storage_path, session_id, filename) if os.path.exists(filepath): os.remove(filepath) data = data.encode('utf8', 'replace') with open(filepath, 'w') as fout: # write image file if output_format == 'svg': cairosvg.svg2svg(bytestring=data, write_to=fout) elif output_format == 'png': cairosvg.svg2png(bytestring=data, write_to=fout) elif output_format == 'pdf': cairosvg.svg2pdf(bytestring=data, write_to=fout) else: pass return serve_file(filepath, 'application/x-download', 'attachment')
def export_pdf(): import cairosvg print("request.form:", request.form) svg_xml = request.form.get("data", "Invalid data") print("svg_xml:", svg_xml) filename = request.form.get("filename", "interval_map_pdf") filepath = "/home/zas1024/gene/wqflask/output/"+filename pdf_file = cairosvg.svg2pdf(bytestring=svg_xml) response = Response(pdf_file, mimetype="application/pdf") response.headers["Content-Disposition"] = "attachment; filename=%s"%filename return response
def export_pdf(): import cairosvg logger.info("request.form:", request.form) svg_xml = request.form.get("data", "Invalid data") logger.info("svg_xml:", svg_xml) filename = request.form.get("filename", "interval_map_pdf") filepath = GENERATED_IMAGE_DIR+filename pdf_file = cairosvg.svg2pdf(bytestring=svg_xml) response = Response(pdf_file, mimetype="application/pdf") response.headers["Content-Disposition"] = "attachment; filename=%s"%filename return response
def svg2pdf(request): logger.info("Called svg2pdf") try: parameters = json.loads(request.body.decode("utf-8")) svg = parameters["svg"] except: raise SuspiciousOperation("Invalid input for svg2pdf.") response = HttpResponse(content_type="application/pdf") response.write(cairosvg.svg2pdf(bytestring=svg)) response["Content-Disposition"] = "attachment; filename=graph.pdf" return response
def installMedia(): # ============================================================================== LOG.msg("install *Media-API* book : %s" % LINUX_TV_BOOK) if LINUX_TV_BOOK.EXISTS: for name in LINUX_TV_BOOK.reMatchFind("[^(conf.py)]"): name.delete() else: LINUX_TV_BOOK.makedirs() fileList = getFileList() for xmlFile in fileList: rstFile = xmlFile.suffix(".rst") src = LINUX_TV_CACHE / rstFile dst = LINUX_TV_BOOK / rstFile if rstFile == FSPath("media_api.rst"): dst = LINUX_TV_BOOK / FSPath("index.rst") folder = FSPath(RESOUCE_FORMAT % src.SKIPSUFFIX) dst.DIRNAME.makedirs() LOG.msg("install file %s" % dst) src.copyfile(dst) if folder.EXISTS: dstFolder = dst.DIRNAME / folder.BASENAME LOG.msg("install files of folder %s" % dstFolder) folder.copytree(dstFolder) for svgFile in dstFolder.reMatchFind(r".*\.svg$"): if not svgFile.suffix(".pdf").EXISTS: try: import cairosvg LOG.msg("convert %s to PDF" % svgFile) cairosvg.svg2pdf(url=svgFile, write_to=svgFile.suffix(".pdf")) except ImportError: LOG.error("missing cairosvg, can't convert %s to PDF" % svgFile)
def send_event_ticket(eventUser, lang): ticket = generate_ticket(eventUser, lang) email = EmailMessage() subject = _(u"Ticket for %(event_name)s event") % {'event_name':eventUser.event.name} body = _(u"Hello %(first_name)s %(last_name)s,\n Here is your ticket for %(event_name)s event. \ Please remember to print it and bring it with you the day of the event. \ \n Regards, %(event_name)s team.") % {'event_name': eventUser.event.name, 'first_name': eventUser.user.first_name, 'last_name':eventUser.user.last_name} email.subject = unicode(subject) email.body = unicode(body) email.to = [eventUser.user.email] email.attach('Ticket-' + str(eventUser.id).zfill(12) + '.pdf', cairosvg.svg2pdf(bytestring=ticket), 'application/pdf') email.send(fail_silently=False)
def export(fromDir, targetDir, exportType): print "开始执行转换命令..." files = os.listdir(fromDir) num = 0 for fileName in files: path = os.path.join(fromDir, fileName) if os.path.isfile(path) and fileName[-3:] == "svg": num += 1 fileHandle = open(path) svg = fileHandle.read() fileHandle.close() exportPath = os.path.join(targetDir, fileName[:-3] + exportType) exportFileHandle = open(exportPath, "w") if exportType == "png": cairosvg.svg2png(bytestring=svg, write_to=exportPath) elif exportType == "pdf": cairosvg.svg2pdf(bytestring=svg, write_to=exportPath) exportFileHandle.close() print "Success Export ", exportType, " -> ", exportPath print "已导出 ", num, "个文件"
def dashExport(request, code): """ Handler function to export dashboard to SVG, PDF, or PNG. Args: request: Django request object. exportType: A string corresponding to the format for export. code: A code to identify the serialized data stored in the session field of the Django request. Returns: A file that corresponds to the dashboard encoded by `serial`, in the format requested. Raises: ValueError: Thrown when an invalid export type is passed in. """ if not settings.EXPORT_SERVICE_PORT: raise ValueError('Received an export request, but exporting is not enabled') data = request.session[code] serial = data['serial'] exportType = data['exportType'] svg = _getSvg(request, serial) res, contentType = None, None if exportType == 'svg': res = svg contentType = "image/svg+xml" else: import cairosvg # pylint: disable = E1101 # Pylint does not recognize svg2pdf/svg2png method in cairosvg if exportType == 'pdf': res = cairosvg.svg2pdf(svg) contentType = "application/pdf" elif exportType == 'png': res = cairosvg.svg2png(svg) contentType = "image/png" else: raise ValueError("views.export.dashExport: Invalid export format, %s" % exportType) response = HttpResponse(res, content_type=contentType) response['Content-Disposition'] = "attachment;filename=dashboard." + exportType return response
def export(): svg_xml = request.form.get("data", "Invalid data") filename = request.form.get("filename") type_foo = request.form['format'] if (type_foo == 'svg'): response = Response(svg_xml, mimetype="image/svg+xml") response.headers["Content-Disposition"] = "attachment; filename=%s"%filename return response elif (type_foo == 'pdf'): pdfOut = cairosvg.svg2pdf(svg_xml) ret = make_response(pdfOut) ret.headers['Content-Type'] = 'application/pdf' ret.headers['Content-Disposition'] = \ 'inline; filename=%s.pdf' return ret elif (type_foo == 'png'): pngOut = cairosvg.svg2png(svg_xml) ret = make_response(pngOut) ret.headers['Content-Type'] = 'image/png' ret.headers['Content-Disposition'] = 'attachment; filename='+filename return ret else: return render_template("error.html")
def outputtemplateonepage(self, listchar): ElementTree.register_namespace('', self.SVGNS) ElementTree.register_namespace('xlink', "http://www.w3.org/1999/xlink") with open(PAPERTEMPLATE, 'r') as f: strsvg = f.read() strdeclaration = strsvg[:strsvg.find("<svg")] xmltree = ElementTree.parse(PAPERTEMPLATE) xmlroot = xmltree.getroot() xmlroot.set('xmlns:xlink', "http://www.w3.org/1999/xlink") #print(xmlroot.attrib) a4pxwidth, a4pxheight = self._getsize(xmlroot) dpmm = a4pxwidth / A4WIDTH_MM #TODO size conversion is needed in case DPI of the two SVG files not matched. assert dpmm == self.tiledpmm, "DPI not matched" # calclulate how many columns and rows can be inserted placeholder = xmlroot.find(".//*[@id='placeholder']") assert placeholder.tag == "{%s}rect"%self.SVGNS, "<rect id=placeholder> not found" rectph = self._getrectfromelem(placeholder) inbetween = 3.0 * dpmm # 3mm margin = (3.0 * dpmm, 0 * dpmm, 3 * dpmm, 2.0 * dpmm) # t,r,b,l ncol, nrow = self._getmaxrowcol(rectph, self.tilesize, inbetween, margin) #if xmlroot has <defs> tag, append tile group to it. if not, create <defs>. defstag = xmlroot.find('{%s}defs'%self.SVGNS) if not defstag: defstag = ElementTree.Element("defs") # or {self.SVGNS}defs ? xmlroot.append(defstag) defstag.append(self.tilegroup) # maybe it's better to do centering for ny in range(nrow): for nx in range(ncol): posx = rectph.x + margin[3] + nx*(self.tilesize[0]+inbetween) posy = rectph.y + margin[0] + ny*(self.tilesize[1]+inbetween) if ny == nrow - 1 and nx == ncol - 1: #right bottom corner a = self.rectdrawarea.mm() #inside A = self.rectscanarea.mm() #outside qrstr = "{:d}:{:d}:{:d},{:d}:{:d}:{:d}".format( a.x - A.x, a.w, A.x + A.w - a.x - a.w, a.y - A.y, a.h, A.y + A.h - a.y - a.h) qrrect = self.rectscanarea.addoffset((posx, posy)) imagetag = self._getqrtag(qrstr, qrrect) xmlroot.append(imagetag) continue #<use xlink:href="#tilegroup" x="10" y="10"/> usetag = ElementTree.Element("use") usetag.set("xlink:href", "#tilegroup") usetag.set("x", str(posx)) usetag.set("y", str(posy)) xmlroot.append(usetag) if listchar: c = listchar.pop(0) #TODO if (str, glyphname) is given instead of str in the list, # the function will set strname as a printed text, and glyphname for # the QR code if isinstance(c, str): texttag = ElementTree.Element("text") texttag.text = c texttag.set("style", "font-size:10pt;") texttag.set("x", str(posx + self.textpos[0])) texttag.set("y", str(posy + self.textpos[1])) xmlroot.append(texttag) qrstr = "{:04X}".format(ord(c)) qrrect = self.rectqrarea.addoffset((posx, posy)) imagetag = self._getqrtag(qrstr, qrrect) xmlroot.append(imagetag) else: continue rectsize = inbetween for ny in range(1,nrow): posx = rectph.x posy = rectph.y + margin[0] + ny*(self.tilesize[1]+inbetween) - inbetween/2 linetag = ElementTree.Element("line") linetag.set("style", "stroke:#B9FFFF;stroke-width:0.2835;") linetag.set("x1", str(posx)) linetag.set("y1", str(posy)) linetag.set("x2", str(posx+rectph.w)) linetag.set("y2", str(posy)) xmlroot.append(linetag) recttag = ElementTree.Element("rect") recttag.set("style", "fill:#000000;") recttag.set("x", str(posx-rectsize/2)) recttag.set("y", str(posy-rectsize/2)) recttag.set("width", str(rectsize)) recttag.set("height", str(rectsize)) xmlroot.append(recttag) for nx in range(1,ncol): posx = rectph.x + margin[3] + nx*(self.tilesize[0]+inbetween) - inbetween/2 posy = rectph.y linetag = ElementTree.Element("line") linetag.set("style", "stroke:#B9FFFF;stroke-width:0.2835;") linetag.set("x1", str(posx)) linetag.set("y1", str(posy)) linetag.set("x2", str(posx)) linetag.set("y2", str(posy+rectph.h)) xmlroot.append(linetag) recttag = ElementTree.Element("rect") recttag.set("style", "fill:#000000;") recttag.set("x", str(posx-rectsize/2)) recttag.set("y", str(posy-rectsize/2)) recttag.set("width", str(rectsize)) recttag.set("height", str(rectsize)) xmlroot.append(recttag) # write svg bstrxml = ElementTree.tostring(xmlroot, method='xml') outsvg = strdeclaration.replace("iso-8859-1","utf-8").encode('utf-8') + bstrxml iopdf = io.BytesIO() cairosvg.svg2pdf(bytestring=outsvg, write_to=iopdf, dpi=self.tiledpmm*25.4) iopdf.seek(0, io.SEEK_SET) return iopdf
def generate_award_pdf(output, data, template_file): with open(template_file) as f: template = unicode(f.read()) shorten_schools(data) pages = u"".join(page.format(**participant) for participant in data) cairosvg.svg2pdf(template.format(pages), write_to=output)
#!/usr/bin/env python # -*- coding: utf-8 -*- import svglue # load the template from a file tpl = svglue.load(file='sample-tpl.svg') # replace some text tpl.set_text('sample-text', u'This was replaced.') # replace the pink box with 'hello.png'. if you do not specify the mimetype, # the image will get linked instead of embedded tpl.set_image('pink-box', file='hello.png', mimetype='image/png') # svgs are merged into the svg document (i.e. always embedded) tpl.set_svg('yellow-box', file='Ghostscript_Tiger.svg') # to render the template, cast it to a string. this also allows passing it # as a parameter to set_svg() of another template src = str(tpl) # write out the result as an SVG image and render it to pdf using cairosvg import cairosvg with open('output.pdf', 'w') as out, open('output.svg', 'w') as svgout: svgout.write(src) cairosvg.svg2pdf(bytestring=src, write_to=out)
def svg2pdf(data): return cairosvg.svg2pdf(data)
def panel(request): if len(request.POST) == 0: return redirect(prog_type+'/HitWalker2/') elif request.POST.has_key("output_format") and request.POST.has_key("data"): try: import cairosvg #and all the somewhat invisible dependencies needed to use external css styling on the svgs... import lxml import tinycss import cssselect if request.POST["plot_type"] == 'svg': use_svg = '<?xml-stylesheet type="text/css" href="' + request.session['new_css_path'] + '" ?>' + request.POST["data"] else: if request.POST['panel_context'] == 'image': width = str(config.pathway_sizes['w'] + config.pathway_sizes['legend_offset']) height = str(config.pathway_sizes['h']) transl = 'translate('+str(config.pathway_sizes['legend_offset'])+',0)' elif request.POST['panel_context'] == 'panel': if request.POST["plot_type"] == 'g1': width=str(config.network_sizes['w']+config.network_sizes['legend_offset']) transl = 'translate('+str(config.pathway_sizes['legend_offset'])+',0)' elif request.POST["plot_type"] == 'siRNA_plot': width=str((config.network_sizes['w']*2)+50) transl='translate(50,0)' else: raise Exception('Unknown plot_type') height = str(config.network_sizes['h']) else: raise Exception('Unknown value for panel_context') use_data = '<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'" >' + request.POST["data"].replace('xmlns="http://www.w3.org/2000/svg"', "") + '</svg>' import xml.etree.ElementTree as ET tree = ET.fromstring(use_data) #ensure everything will fit on screen #assuming only one non-legend g for now tree.find("./*[@class=\'"+request.POST["plot_type"]+"\']").attrib['transform'] = transl sub_tree = tree.find(".//*[@class='BorderRect BorderSelected']/..") if sub_tree != None: tree.find(".//*[@class='BorderRect BorderSelected']/..").remove(tree.find(".//*[@class='BorderRect BorderSelected']")) use_svg = '<?xml-stylesheet type="text/css" href="' + request.session['new_css_path'] + '" ?>' + ET.tostring(tree) temp_file = tempfile.mktemp() #temp_file = '/Users/bottomly/Desktop/test_image.xml' temp_inp = open(temp_file, "w") temp_inp.write(use_svg) temp_inp.close() if request.POST["output_format"] == "svg": response = HttpResponse(cairosvg.svg2svg(url=temp_file), content_type='image/svg+xml') response['Content-Disposition'] = 'attachment; filename="HitWalker2.svg"' elif request.POST["output_format"] == "pdf": response = HttpResponse(cairosvg.svg2pdf(url=temp_file), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="HitWalker2.pdf"' return response except ImportError, e: raise e response = HttpResponse('<?xml-stylesheet type="text/css" ?>' + request.POST["data"], content_type='image/svg+xml') response['Content-Disposition'] = 'attachment; filename="HitWalker2.svg"' return response
foreground_light='blue', foreground_dark='black', opacity='.6', opacity_hover='.9', transition='400ms ease-in') temp_1 = os.path.join(temp, 'result.svg') bar_chart = pygal.Line(style=custom_style,legend_at_bottom=True) # Then create a bar graph object bar_chart.title = sys.argv[2] bar_chart.x_labels = head #map(str, range(2002, 2013)) #bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]) # Add some values #bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12]) for row in data : final_data = [] for elem in row["data"] : final_data.append(float(elem)) bar_chart.add(row["title"],final_data) bar_chart.render_to_file(temp_1) # Save the svg to a file aFile = os.path.join(sys.argv[4],"bar_chart." + sys.argv[5]) sys.stdout.write(aFile) with open(temp_1, 'rb') as file_object: svg_content = file_object.read() with open( aFile, 'wb') as file_object: # Write to a real file object if sys.argv[5] == "pdf" : cairosvg.svg2pdf(svg_content, write_to=file_object) else : cairosvg.svg2png(svg_content, write_to=file_object) shutil.rmtree(temp)
def convert_to_pdf(response): response.content = cairosvg.svg2pdf(bytestring=response.content) return response
def main(argv): parser = argparse.ArgumentParser() parser.add_argument("AB0", help="Cross relation AB in line 0",default=0.40, type=float) parser.add_argument("AC0", help="Cross relation AC in line 0",default=0.60, type=float) parser.add_argument("AB1", help="Cross relation AB in line 1",default=0.20, type=float) parser.add_argument("AC1", help="Cross relation AC in line 1",default=0.80, type=float) parser.add_argument("--marker_size", help="Length from center of top-left circle to center of top-right circle (cm)", default=10.0, type=float) parser.add_argument("--circle_clearance", help="White space around each black circle in cm", default=0.2, type=float) parser.add_argument("--circle_radius", help="Radius of each circle (cm)", default=0.9, type=float) parser.add_argument("--output_file", help="Name of the output file", type=str, default="pitag_marker.svg") parser.add_argument("--A4", help="SVG output centered in A4 sheet size",action="store_true") parser.add_argument("--pdf", help="Convert final SVG file to pdf",action="store_true") parser.add_argument("--show_info", help="Print additional information inside the marker",action="store_true") #parser.add_argument("--print_debug", help="Print debug information inside the marker",action="store_true") args = parser.parse_args() file_name = os.path.splitext(args.output_file)[0] if args.A4: w, h = 21.0,29.7 dwg = svgwrite.Drawing(filename=file_name+'.svg', size=(w*cm, h*cm), debug=True) dwg.add(dwg.rect(insert=(0,0), size=(w*cm, h*cm), fill='white', stroke='none')) else: w, h = '100%', '100%' dwg = svgwrite.Drawing(filename=file_name+'.svg', size=(w, h), debug=True) dwg.add(dwg.rect(insert=(0,0), size=(w, h), fill='white', stroke='none')) #The four corners of the square marker_size = args.marker_size circle_radius = args.circle_radius circle_clearance = args.circle_clearance #CrossRatios 0 - 1.0 relative to marker_size d_line0_AB = marker_size * args.AB0 #AB d_line0_BD = marker_size - marker_size *args.AB0 #BD d_line0_AC = marker_size * args.AC0 #//AC d_line0_CD = marker_size - marker_size * args.AC0 #//CD cross_ration_0 = (d_line0_AB/d_line0_BD)/(d_line0_AC/d_line0_CD) d_line1_AB = marker_size * args.AB1 #AB d_line1_BD = marker_size - marker_size *args.AB1 #BD d_line1_AC = marker_size * args.AC1 #;//AC d_line1_CD = marker_size - marker_size * args.AC1 #;//CD cross_ration_1 = (d_line1_AB/d_line1_BD)/(d_line1_AC/d_line1_CD) print "cross_ration 0: {0}".format(cross_ration_0) print "cross_ration 1: {0}".format(cross_ration_1) print "delta:{0}".format(cross_ration_0 / cross_ration_1) if cross_ration_0 < cross_ration_1: print "Error, Crossratio 0 must be greater that Crossratio 1" sys.exit() CR_Line0_AB = args.AB0 CR_Line0_AC = args.AC0 CR_Line1_AB = args.AB1 CR_Line1_AC = args.AC1 #center of the marker cx = cy = circle_clearance + circle_radius + marker_size/2 #Squares for marker size reference size_inner_square = marker_size-circle_radius*2-circle_clearance*2 corner_inner_square = 2*circle_radius + 2*circle_clearance size_outer_square = marker_size+circle_radius*2+circle_clearance*2 #We create a group for the whole marker marker = dwg.defs.add(dwg.g(id='marker')) #Outer square marker.add(svgwrite.shapes.Rect((0*cm,0*cm),(size_outer_square*cm,size_outer_square*cm), fill='white', stroke='black')) #inner square marker.add(svgwrite.shapes.Rect((corner_inner_square*cm,corner_inner_square*cm),(size_inner_square*cm,size_inner_square*cm), fill='none', stroke='black')) x1 = y1 = circle_radius + circle_clearance x2 = y2 = circle_radius + circle_clearance + marker_size #lets draw the marker corner circles top_left_corner = (x1*cm,y1*cm) bottom_left_corner = (x1*cm,y2*cm) top_right_corner = (x2*cm,y1*cm) bottom_right_corner = (x2*cm,y2*cm) marker.add(svgwrite.shapes.Circle(top_left_corner, circle_radius*cm)) marker.add(svgwrite.shapes.Circle(bottom_left_corner, circle_radius*cm)) marker.add(svgwrite.shapes.Circle(top_right_corner, circle_radius*cm)) marker.add(svgwrite.shapes.Circle(bottom_right_corner, circle_radius*cm)) #Now we draw the Cross related circles for line 0 marker.add(svgwrite.shapes.Circle(((x1+marker_size*CR_Line0_AB)*cm,y1*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle((x1*cm,(y1+marker_size*CR_Line0_AB)*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle(((x1+marker_size*CR_Line0_AC)*cm,y1*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle((x1*cm,(y1+marker_size*CR_Line0_AC)*cm), circle_radius*cm)) #Now we draw the Cross related circles for line 1 marker.add(svgwrite.shapes.Circle(((x1+marker_size*CR_Line1_AB)*cm,y2*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle((x2*cm,(y1+marker_size*CR_Line1_AB)*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle(((x1+marker_size*CR_Line1_AC)*cm,y2*cm), circle_radius*cm)) marker.add(svgwrite.shapes.Circle((x2*cm,(y1+marker_size*CR_Line1_AC)*cm), circle_radius*cm)) #Put text with information about the marker in the center t_x = cx - 5 t_y = cy + size_outer_square/2 +1 if args.show_info: marker.add(dwg.text('| AB | BD | CD |', insert=((t_x+3)*cm, t_y*cm), fill='black', textLength = 10*cm)) marker.add(dwg.text('| {0:.3f}cm | {1:.3f}cm | {2:.3f}cm |'.format(d_line0_AB,d_line0_BD,d_line0_CD), insert=((t_x+3)*cm, (t_y+0.5)*cm), fill='black')) marker.add(dwg.text('| {0:.3f}cm | {1:.3f}cm | {2:.3f}cm |'.format(d_line1_AB,d_line1_BD,d_line1_CD), insert=((t_x+3)*cm, (t_y+1.0)*cm), fill='black')) marker.add(dwg.text('Line Top:', insert=((t_x)*cm, (t_y+0.5)*cm), fill='black')) marker.add(dwg.text('Line Bottom:', insert=((t_x)*cm, (t_y+1.0)*cm), fill='black')) marker.add(dwg.text('Marker Size = {0}cm'.format(marker_size), insert=((t_x)*cm, (t_y+2)*cm), fill='black')) marker.add(dwg.text('Circle Radius = {0}cm'.format(circle_radius), insert=((t_x)*cm, (t_y+2+0.5)*cm), fill='black')) marker.add(dwg.text('Circle Clearance = {0}cm'.format(circle_clearance), insert=((t_x)*cm, (t_y+2+1.0)*cm), fill='black')) marker.add(dwg.text('Cross-ratio 0: AB = {0:2.2f}, AC= {1:.2f}, CR= {2:.4f}'.format(CR_Line0_AB,CR_Line0_AC, cross_ration_0,4), insert=((t_x)*cm, (t_y+2+1.5)*cm), fill='black')) marker.add(dwg.text('Cross-ratio 1: AB = {0:2.2f}, AC= {1:.2f}, CR= {2:.4f}'.format(CR_Line1_AB,CR_Line1_AC, cross_ration_1,4), insert=((t_x)*cm, (t_y+2+2)*cm), fill='black')) d_line0_AB = marker_size * args.AB0 #AB d_line0_BD = marker_size - marker_size *args.AB0 #BD d_line0_AC = marker_size * args.AC0 #//AC d_line0_CD = marker_size - marker_size * args.AC0 #//CD cross_ration_0 = (d_line0_AB/d_line0_BD)/(d_line0_AC/d_line0_CD) d_line1_AB = marker_size * args.AB1 #AB d_line1_BD = marker_size - marker_size *args.AB1 #BD d_line1_AC = marker_size * args.AC1 #;//AC d_line1_CD = marker_size - marker_size * args.AC1 #;//CD #red do in the Center of the marker marker.add(svgwrite.shapes.Circle((cx*cm,cy*cm), 0.05*cm, fill='red')) marker.add(dwg.line((cx*cm, cy*cm), ((cx+2)*cm, cy*cm), stroke=svgwrite.rgb(10, 10, 16, '%'))) marker.add(dwg.line((cx*cm, cy*cm), (cx*cm, (cy-2)*cm), stroke=svgwrite.rgb(10, 10, 16, '%'))) marker.add(dwg.text('x', insert=((cx+2.1)*cm, (cy)*cm), fill='black')) marker.add(dwg.text('y', insert=((cx)*cm, (cy-2.2)*cm), fill='black')) if args.A4: #center marker in middle of A4 sheet x_m = ((w/2)-(size_outer_square/2)) y_m = ((h/2)-(size_outer_square/2)) u = dwg.use(marker, insert=(x_m*cm,y_m*cm)) else: u = dwg.use(marker, insert=(0*cm,0*cm)) dwg.add(u) dwg.save() if args.pdf: cairosvg.svg2pdf(file_obj=open(file_name+'.svg', "rb"), write_to=file_name+'.pdf')
def convert(self, _from, _to): # type: (unicode, unicode) -> bool """Converts the image to expected one.""" svg2pdf(url=_from, write_to=_to) return True
#!/usr/bin/env python # -*- coding: utf-8 -*- import cairosvg filename = input('Please enter filename:>>') cairosvg.svg2pdf( file_obj=open(filename+'.svg', "rb"), write_to=filename+'.pdf') input('请按任意键退出')
def create_certificate(template_path, output_path, params): '''Create a single certificate.''' with open(template_path, 'r') as reader: template = reader.read() check_template(template, params) for key, value in params.items(): pattern = '{{' + key + '}}' template = template.replace(pattern, value) tmp = tempfile.NamedTemporaryFile(suffix='.svg', delete=False) tmp.write(bytes(template, 'utf-8')) cairosvg.svg2pdf(url=tmp.name, write_to=output_path, dpi=90)