def render_flow(self, outfilename, **kwargs): """ Renders the report template to pdf with the given kwargs while yielding statuses. Warning: This function does a sleep between genshi rendering and PDF gen to avoid crash of rml2pdf. @param outfilename: the filename of the pdf to write. @type outfilename: string @kwargs: all the vars you want to pass to genshi context """ # Creating temp file for rml output temp_fname = self.__generate_tempfile() temp_file = codecs.open(temp_fname, 'wb+', 'utf-8') yield True # Writing RML output for status in self.process_write(temp_file, **kwargs): yield status temp_file.close() yield True # Sleeping to avoid crash of rml2pdf time.sleep(0.1) # Writing PDF from RML rml2pdf.go(temp_fname, outfilename) yield True # Cleaning temp file self.__clean_tempfile(temp_fname) yield True
def main(infilename): # First print out some environment information outdir = os.path.join(os.path.abspath(os.path.curdir), 'output') if not os.path.isdir(outdir): os.mkdir(outdir) # First we do this test ten times, and gather testdata = {} testfilenames = {} different_files = [] for i in range(10): pdf_filename = os.path.join(outdir, 'test-%02i.pdf' % i) rml2pdf.go(infilename, pdf_filename) # Remove old png files. for filename in glob.glob(os.path.join(outdir, 'test-%02i*.png' % i)): os.unlink(filename) # Now convert this to PNG, and save that data os.system(gs_command(pdf_filename)) # Load the images generated png_files = glob.glob(os.path.join(outdir, 'test-%02i*.png' % i)) testdata[i] = {} testfilenames[i] = {} for k, filename in enumerate(sorted(png_files)): testdata[i][k] = get_image_data(filename) testfilenames[i][k] = filename # Then convert it 2 more times, for a total of 3, and check that the # output is the same every time. This is to test that Ghostscript # will create the same PNG every time from the same source. for j in range(2): # Convert again os.system(gs_command(pdf_filename)) png_files = glob.glob(os.path.join(outdir, 'test-%02i*.png' % i)) for k, filename in enumerate(sorted(png_files)): testimage = get_image_data(filename) # This whole test is based on the assumption that ghostscrip # creates the same PNG on multiple runs, so if this is untrue # we can just as well just fail. assert testdata[i][k] == testimage # Lastly check that each PDF conversion is the same, pixel by pixel for k, filename in enumerate(sorted(png_files)): # Sanity check assert filename == testfilenames[i][k] # Check that the data is the same if testdata[i][k] != testdata[0][k]: different_files.append((filename, testfilenames[0][k])) print("Result\n======") print("%s files out of 27 was different from the first run:" % len(different_files)) for files in different_files: print("%s was different from %s" % files) if different_files: raise RuntimeError("Found a difference!")
def generate_one_invoice(family, class_map, note, term, output_file): rml = io.StringIO() start_rml(rml, template=RML_BEGIN_TEMPLATE_PORTRAIT, title='Class Enrollment Invoice', term=term) invoice = create_invoice_object(family, class_map, note) generate_invoice_page_rml(invoice, rml) finish_rml(rml) rml.seek(0) rml2pdf.go(rml, outputFileName=output_file)
def create_pdf_from_batch(self, batch): template = pyratemp.Template(filename=self.TEMPLATE_FILENAME, parser_class=DjangoFormatParser) cards = batch.registration_numbers.all() rml = six.BytesIO(self.parse_template(template, cards)) unused, filename = tempfile.mkstemp() try: rml2pdf.go(rml, filename) # This closes the file new_filename = "{}.pdf".format(time.strftime("%m%d%H%M%S")) with open(filename) as fh: batch.data_file.save(name=new_filename, content=File(fh)) finally: os.unlink(filename)
def generate_master(families, class_map, term, output_file): rml = io.StringIO() start_rml(rml, template=RML_BEGIN_TEMPLATE_PORTRAIT, title='Class Enrollment Master List', term=term, footer='Page <pageNumber/>') for family in families.values(): if get_students(family): generate_master_rml_for_family(family, class_map, rml) finish_rml(rml) # logger.debug('rml: %s', rml.getvalue()) rml.seek(0) rml2pdf.go(rml, outputFileName=output_file)
def render(self, outfilename, **kwargs): """ Renders the report template to pdf with the given kwargs. Warning: This function does a sleep between genshi rendering and PDF gen to avoid crash of rml2pdf. @param outfilename: the filename of the pdf to write. @type outfilename: string @kwargs: all the vars you want to pass to genshi context """ # Creating temp file for rml output temp_fname = self.__generate_tempfile() temp_file = codecs.open(temp_fname, 'wb+', 'utf-8') # Writing RML output self.write(temp_file, should_close=True, **kwargs) # Sleeping to avoid crash of rml2pdf time.sleep(0.1) # Writing PDF from RML result = rml2pdf.go(temp_fname, outfilename) # Cleaning temp file self.__clean_tempfile(temp_fname) return result
def render(self, outfilename, **kwargs): """ Renders the report template to pdf with the given kwargs. Warning: This function does a sleep between genshi rendering and PDF gen to avoid crash of rml2pdf. @param outfilename: the filename of the pdf to write. @type outfilename: string @kwargs: all the vars you want to pass to genshi context """ # Creating temp file for rml output temp_fname = self.__generate_tempfile() temp_file = codecs.open(temp_fname, 'wb+', 'utf-8') # Writing RML output self.write(temp_file, should_close=True, **kwargs) # Sleeping to avoid crash of rml2pdf time.sleep(0.1) # Writing PDF from RML result = rml2pdf.go(temp_fname, outfilename, **kwargs) # Cleaning temp file self.__clean_tempfile(temp_fname) return result
def test_duplicate_key(self): save_strict = pdfinclude.STRICT inpath = os.path.join(HERE, 'input', 'data', 'tag-includePdfPages-edge-dupekey.rml') outpath = os.path.join(HERE, 'output', 'tag-includePdfPages-edge-dupekey.pdf') # in strict mode include will fail because the PDF is bad pdfinclude.STRICT = True with self.assertRaises(PdfReadError): rml2pdf.go(inpath, outpath) # in non strict mode such errors are demoted to warnings pdfinclude.STRICT = False rml2pdf.go(inpath, outpath) pdfinclude.STRICT = save_strict
def excecuteSubProcess(xmlInputName, outputFileName, testing=None): # set the sys path given from the parent process sysPath = os.environ['Z3CRMLSYSPATH'] sys.path[:] = sysPath.split(';') # now it come the ugly thing, but we need to hook our test changes into # our subprocess. if testing is not None: # set some globals import z3c.rml.attr import z3c.rml.directive global _fileOpen _fileOpen = z3c.rml.attr.File.open def testOpen(img, filename): # cleanup win paths like: # ....\\input\\file:///D:\\trunk\\... if sys.platform[:3].lower() == "win": if filename.startswith('file:///'): filename = filename[len('file:///'):] path = os.path.join(os.path.dirname(xmlInputName), filename) return open(path, 'rb') # override some testing stuff for our tests z3c.rml.attr.File.open = testOpen import z3c.rml.tests.module sys.modules['module'] = z3c.rml.tests.module sys.modules['mymodule'] = z3c.rml.tests.module # import rml and process the pdf from z3c.rml import rml2pdf rml2pdf.go(xmlInputName, outputFileName) if testing is not None: # reset some globals z3c.rml.attr.File.open = _fileOpen del sys.modules['module'] del sys.modules['mymodule']
def generate_invoices(progress, families, class_map, note, term, output_file): rml = io.StringIO() start_rml(rml, template=RML_BEGIN_TEMPLATE_PORTRAIT, title='Class Enrollment Invoice', term=term) for n, family in enumerate(families.values()): if progress.WasCancelled(): break msg = "Please wait...\n\n" \ f"Generating invoice for family: {family['last_name']}" # logger.debug(f'updating progress {n}: {msg}') progress.Update(n, newmsg=msg) students = get_students(family) if students: logger.debug( f'processing {len(students)} students in family {n}: {family["last_name"]}' ) invoice = create_invoice_object(family, class_map, note) generate_invoice_page_rml(invoice, rml) finish_rml(rml) # logger.debug('rml: %s', rml.getvalue()) rml.seek(0) rml2pdf.go(rml, outputFileName=output_file)
def runTest(self): rml2pdf.go(self._inPath, self._outPath)
''' pip install z3c.rml ''' from z3c.rml import rml2pdf rml2pdf.go('07.xml','output/07.pdf')
def create_pdf(files, template,first_page_title_size="38",first_page_title_x="80",first_page_title_y="700",first_page_title_font="Helvetica-Bold", first_page_title=" ",first_page_title_color="blue",question_top_padding="35",question_bottom_padding="55",question_numbers_offsetY="-30", both_side_mode="True",pages_bottom_title="xysinav",pages_bottom_title_font="Helvetica-Bold",pages_bottom_title_size="10",pages_bottom_title_color="black", pdf_filename="output",question_count="2"): #RML_DIR = 'rml-files' content = """<?xml version="1.0" encoding="UTF-8" standalone="no" ?> <!DOCTYPE document SYSTEM "rml.dtd"> <document filename="harwoodgame_flyer.pdf" xmlns:doc="http://namespaces.zope.org/rml/doc"> <docinit> <registerTTFont faceName="Arial" fileName="/Users/emreulgac/PycharmProjects/pdfgenerator/fontlar/Arial.ttf"/> <registerTTFont faceName="Nunito-Regular" fileName="/Users/emreulgac/PycharmProjects/pdfgenerator/fontlar/Nunito-Regular.ttf"/> <registerTTFont faceName="Helvetica" fileName="/Users/emreulgac/PycharmProjects/pdfgenerator/fontlar/Helvetica.ttf"/> <registerTTFont faceName="HelveticaNeue-Light" fileName="/Users/emreulgac/PycharmProjects/pdfgenerator/fontlar/LTe50263.ttf"/> <registerTTFont faceName="HelveticaNeue-Bold" fileName="/Users/emreulgac/PycharmProjects/pdfgenerator/fontlar/LTe50261.ttf"/> </docinit> <template pageSize="(595, 842)" leftMargin="50" topMargin="30" showBoundary="0"> <pageTemplate id="front-page"> <pageGraphics> <image file="/Users/emreulgac/PycharmProjects/pdfgenerator/rml-files/front-1.jpg" x="0" y="0" width="595" height="842"/> <fill color="red"/> <setFont name="Helvetica" size="12"/> <drawCenteredString x="297" y="40"></drawCenteredString> <fill color="{first_page_titlecolor}"/> <setFont name="{first_page_title_font}" size="{first_page_title_size}"/> <drawString x="{first_page_title_x}" y="{first_page_title_y}">{first_page_title}</drawString> </pageGraphics> <frame id="main" x1="5%" y1="8%" width="43%" height="90%"/> </pageTemplate> <pageTemplate id="questions"> <pageGraphics> <image file="/Users/emreulgac/PycharmProjects/pdfgenerator/rml-files/p1.jpg" x="0" y="80" width="595" height="750" /> <fill color="red"/> <setFont name="Helvetica" size="12"/> <drawCenteredString x="297" y="40"></drawCenteredString> <image file="/Users/emreulgac/PycharmProjects/pdfgenerator/rml-files/logo.jpg" x="15" y="755" width="100" height="100"/> <fill color= "blue" /> <rect x="30" y = "45" width="535" height="1" round="1" stroke="0" fill="1" /> <fill color="black"/> <drawString x="32" y="30">{first_page_title}</drawString> <fill color="black"/> <drawString x="297" y="30"><pageNumber/></drawString> <fill color="black"/> <drawString x="447" y="30">Diğer sayfaya geçiniz</drawString> <fill color= "blue" /> <rect x="30" y = "22" width="535" height="1" round="1" fill="1" stroke="0" /> </pageGraphics> {both_side_mode} </pageTemplate> <pageTemplate id="questions-2"> <pageGraphics> <image file="/Users/emreulgac/PycharmProjects/pdfgenerator/rml-files/p2.jpg" x="0" y="80" width="595" height="750" /> <fill color="red"/> <setFont name="Helvetica" size="12"/> <drawCenteredString x="297" y="40"></drawCenteredString> <image file="/Users/emreulgac/PycharmProjects/pdfgenerator/rml-files/logo.jpg" x="15" y="755" width="100" height="100"/> <fill color= "blue" /> <rect x="30" y = "45" width="535" height="1" round="1" stroke="0" fill="1" /> <fill color="black"/> <drawString x="32" y="30">{first_page_title}</drawString> <fill color="black"/> <drawString x="297" y="30"><pageNumber/></drawString> <fill color="black"/> <drawString x="447" y="30">Diğer sayfaya geçiniz</drawString> <fill color= "blue" /> <rect x="30" y = "22" width="535" height="1" round="1" fill="1" stroke="0" /> </pageGraphics> {both_side_mode} </pageTemplate> </template> <stylesheet> <paraStyle name="h1" fontName="Helvetica" fontSize="27" leading="17" spaceBefore = "30" /> <paraStyle name="front-h1" fontName="Helvetica" fontSize="27" leading="17" spaceBefore="10in" /> <paraStyle name="h2" fontName="Helvetica" fontSize="15" leading="17" spaceBefore = "15" /> <paraStyle name="prod_name" fontName="Helvetica" fontSize="14.5" leading="14" spaceBefore = "14" /> <paraStyle name="prod_summary" fontName="Helvetica" fontSize="12" /> <listStyle name="blah" spaceAfter="10" bulletType="A" spaceBefore="23" /> <listStyle name="square" spaceAfter="10" bulletType="bullet" spaceBefore="23" bulletColor="red" start="square"/> <paraStyle name="prod_price" fontName="Helvetica" fontSize="7.5" leading="14" spaceBefore = "4" textColor="green" /> <paraStyle name="normal" fontName="Helvetica" fontSize="10" leading="12" /> <paraStyle name="bullet" parent="normal" bulletFontName = "Helvetica" bulletFontSize="5"/> <listStyle name="Ordered" bulletFontName="Nunito" bulletFontSize="13" bulletFormat="%s." bulletDedent="25" bulletType="1" bulletColor="black" leftIndent="25" bulletOffsetY="{question_numbers_offsetY}" /> </stylesheet> <story> <setNextTemplate name="front-page" /> <setNextTemplate name="questions-2" /> <nextFrame/> <ol style="Ordered" > {images_last} </ol> </story> </document> """ i=0 images_last = " " while i < question_count: print("hallo"+files[i]) if files[i] == '.DS_Store': i = i + 1 images='<li bulletColor="black" bulletFontName="Helvetica"> <imageAndFlowables imageName="/Users/emreulgac/PycharmProjects/pdfgenerator/img/{URL}" imageTopPadding="{question_top_padding}" imageBottomPadding="{question_bottom_padding}"> </imageAndFlowables> </li>' images=images.format(URL=files[i],question_top_padding=question_top_padding,question_bottom_padding=question_bottom_padding) images_last=images_last + images i=i+1 f = open("latest-2.rml", "w+") if both_side_mode == "True": last_content = content.format(first_page_titlecolor=first_page_title_color, first_page_title_size=first_page_title_size, first_page_title_font=first_page_title_font, first_page_title_x=first_page_title_x, first_page_title_y=first_page_title_y, first_page_title=first_page_title, pages_bottom_title_color=pages_bottom_title_color, pages_bottom_title_font=pages_bottom_title_font, pages_bottom_title_size=pages_bottom_title_size , pages_bottom_title=pages_bottom_title,question_numbers_offsetY=question_numbers_offsetY, both_side_mode='<frame id="left" x1="3%" y1="2%" width="42%" height="90%"/> <frame id="right" x1="54%" y1="2%" width="42%" height="90%"/>',images_last=images_last) else: last_content = content.format(first_page_titlecolor=first_page_title_color, first_page_title_size=first_page_title_size, first_page_title_font=first_page_title_font, first_page_title_x=first_page_title_x, first_page_title_y=first_page_title_y, first_page_title=first_page_title, pages_bottom_title_color=pages_bottom_title_color, pages_bottom_title_font=pages_bottom_title_font, pages_bottom_title_size=pages_bottom_title_size , pages_bottom_title=pages_bottom_title,question_numbers_offsetY=question_numbers_offsetY, both_side_mode='<frame id="left" x1="3%" y1="2%" width="44%" height="90%"/>',images_last=images_last) f.write(last_content) f.close() print(last_content) return rml2pdf.go('latest-2.rml',BASE_DIR + '/output/' +pdf_filename +'.pdf')
def run_action(self, src, dest=None, **kwargs): """Convert rml at src to pdf at dest using rml2pdf """ if dest is None: dest = os.path.splitext(src)[0] + ".pdf" rml2pdf.go(src, dest)
#!/usr/bin/env python2.4 import sys from z3c.rml import rml2pdf for arg in sys.argv[1:]: rml2pdf.go(arg)