Ejemplo n.º 1
2
def generatePDF(html_source, verbose, language_code='en', pdf_parameter='openpdf'):
    file_name = 'MuseScore-' + language_code + '.pdf'
    print 'Create PDF handbook:',file_name

    try:
        import ho.pisa as pisa
        if verbose:
            pisa.showLogging()
    except:
        print "\nPisa library required from creating PDFs. See README.txt for information\n"
        return

    #import re
    #html_source = re.sub('(.)','\\1 ',html_source)
    #m = re.search(">([^<]*)<",h)
    #m.group(0)

    #if (language_code == 'ja'):
    #    html_source = insertSpaces(html_source)

    pdf = pisa.CreatePDF(
        html_source,
        file(file_name, "wb"))
    
    if not pdf.err and pdf_parameter=='openpdf':
            pisa.startViewer(file_name)
Ejemplo n.º 2
0
def helloWorld():
    filename = __file__ + ".pdf"
    pdf = pisa.CreatePDF("Hello <strong>World</strong>", file(filename, "wb"))
    if not pdf.err:
        pisa.startViewer(filename)
        if __name__ == "__main__":
            pisa.showLogging()
Ejemplo n.º 3
0
def create_pdf(content, filename):
    print 'Creating PDF...'
    document = HEADER + content + FOOTER
    pisa.showLogging()
    file = open(filename, 'wb')
    pdf = pisa.pisaDocument(document, file, raise_exception=False)
    file.close()
    if pdf.err:
        print 'Error: {}\n'.format(pdf.err)
    else:
        print 'OK\n'
Ejemplo n.º 4
0
def convertHtmlToPdf(sourceHtml, outputFilename):
    pisa.showLogging()
    #print "open output file for writing (truncated binary)", datetime.now().strftime('%H:%M:%S')
    resultFile = open(outputFilename, "w+b")
    #print " convert HTML to PDF", datetime.now().strftime('%H:%M:%S')
    pisaStatus = pisa.CreatePDF(
            sourceHtml.encode("UTF-8"),                # the HTML to convert
            dest=resultFile, encoding='UTF-8',
                   link_callback=fetch_resources)           # file handle to recieve result
    #print " close output file", datetime.now().strftime('%H:%M:%S')
    resultFile.close()                 # close output file
    # return True on success and False on errors
    return pisaStatus.err
Ejemplo n.º 5
0
def report_regiao(request, regiao='NE'):

    if request.POST:
        if 'regiao' in request.POST:
            regiao = request.POST['regiao']

    REGIAO_CHOICES = dict(UnidadeFederativa.REGIAO_CHOICES)

    projetos = Projeto.objects.all()

    camaras = CasaLegislativa.objects.filter(tipo__sigla='CM')

    tabelas = list()
    # Geral
    convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM')
    tabela = casas_estado_to_tabela(camaras, convenios, regiao)
    tabela["projeto"] = _(u"Geral")

    tabelas.append(tabela)

    for projeto in projetos:
        convenios_proj = convenios.filter(projeto=projeto)
        tabela = casas_estado_to_tabela(camaras, convenios_proj, regiao)
        tabela["projeto"] = projeto.nome
        tabelas.append(tabela)

    data = datetime.datetime.now().strftime('%d/%m/%Y')
    hora = datetime.datetime.now().strftime('%H:%M')
    pisa.showLogging()
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=RelatorioRegiao_' + regiao + '.pdf'
    #tabelas = ({'projeto':"PI"},{'projeto':"PML"},)
    t = loader.get_template('convenios/tabela_regiao.html')
    c = Context({
        'tabelas': tabelas,
        'regiao': REGIAO_CHOICES[regiao],
        'data': data,
        'hora': hora
    })
    pdf = pisa.CreatePDF(t.render(c), response)
    if not pdf.err:
        pisa.startViewer(response)

    return response
Ejemplo n.º 6
0
def report_regiao(request,regiao='NE'):
    
    if request.POST:
        if request.POST.has_key('regiao'):
            regiao = request.POST['regiao']

    REGIAO_CHOICES = {
        'SL': 'Sul',
        'SD': 'Sudeste',
        'CO': 'Centro-Oeste',
        'NE': 'Nordeste',
        'NO': 'Norte',
    }
    
    projetos = Projeto.objects.all()
    
    camaras = CasaLegislativa.objects.filter(tipo__sigla='CM')

    tabelas = list()
    # Geral
    convenios = Convenio.objects.filter(casa_legislativa__tipo__sigla='CM')    
    tabela = casas_estado_to_tabela(camaras,convenios,regiao)
    tabela["projeto"] = "Geral"

    tabelas.append(tabela)

    for projeto in projetos:
        convenios_proj = convenios.filter(projeto=projeto)
        tabela = casas_estado_to_tabela(camaras, convenios_proj,regiao)
        tabela["projeto"] = projeto.nome
        tabelas.append(tabela)
    
    data = datetime.datetime.now().strftime('%d/%m/%Y')
    hora = datetime.datetime.now().strftime('%H:%M')    
    pisa.showLogging()
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=RelatorioRegiao_' + regiao + '.pdf'
    #tabelas = ({'projeto':"PI"},{'projeto':"PML"},)
    t = loader.get_template('convenios/tabela_regiao.html')
    c = Context({'tabelas':tabelas,'regiao':REGIAO_CHOICES[regiao],'data':data,'hora':hora})    
    pdf = pisa.CreatePDF(t.render(c),response)
    if not pdf.err:
        pisa.startViewer(response)

    return response
Ejemplo n.º 7
0
def render(hostname, topics, output):
    ''' Save articles in document
    '''
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader('templates'))
    tmpl = env.get_template(hostname)
    import ho.pisa as pisa
    pisa.showLogging()

    import tempfile
    articles = list()
    for topic in topics:
        try:
            content = tmpl.render(articles = (topic,))
            with tempfile.TemporaryFile('wb') as temp:
                pisa.CreatePDF(content.encode('utf-8'), temp)
            articles.append(topic)
        except Exception, exc:
            print "ERROR!!!", exc
Ejemplo n.º 8
0
def write_pdf(html,filename,stream=False,base_folder=''):
    import os
    import ho.pisa as pisa
    import cStringIO as StringIO
    pisa.showLogging()
    def fetch_resources(uri, rel):
        return os.path.join(base_folder,uri)

    path = os.path.join(base_folder,filename) + '.pdf'
    result = StringIO.StringIO() if stream else file(path, "wb")

    pdf = pisa.CreatePDF(
            html,
            result,
#            encoding='UTF-8',
            show_error_as_pdf=True,
#            link_callback=fetch_resources
            )

    if not stream:
        result.close()
        return  path #Retorna o caminho para o arquivo
    else:
        return result #Retorna o stream do arquivo
Ejemplo n.º 9
0
    html = """
            <style>
            @page {
                background: url("%s");
                @frame text {
                    top: 6cm;
                    left: 4cm;
                    right: 4cm;
                    bottom: 4cm;
                    -pdf-frame-border: 1;
                }
            }
            </style>

            <p>
            Hello <strong>World</strong>
            <p>
            <img src="%s">
        """ % (bguri, datauri)
    pdf = pisa.pisaDocument(
        html,
        open(filename, "wb"),
        path = __file__
        )
    if not pdf.err:
        pisa.startViewer(filename)

if __name__=="__main__":
    pisa.showLogging()
    helloWorld()
Ejemplo n.º 10
0
def createPDF(inputFile):
    input = open(inputFile).read()
    output = file(pdf, "wb")
    pisa.showLogging()
    pisa.CreatePDF(input, output)
    output.close()
Ejemplo n.º 11
0
# limitations under the License.

__version__ = "$Revision: 194 $"
__author__  = "$Author: holtwick $"
__date__    = "$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $"

import os
import sys
import cgi
import cStringIO
import logging

import ho.pisa as pisa

# Shortcut for dumping all logs to the screen
pisa.showLogging()

def dumpErrors(pdf, showLog=True):
    #if showLog and pdf.log:
    #    for mode, line, msg, code in pdf.log:
    #        print "%s in line %d: %s" % (mode, line, msg)
    #if pdf.warn:
    #    print "*** %d WARNINGS OCCURED" % pdf.warn
    if pdf.err:
        print "*** %d ERRORS OCCURED" % pdf.err

def testSimple(
    data="""Hello <b>World</b><br/><img src="img/test.jpg"/>""",
    dest="test.pdf"):

    """
Ejemplo n.º 12
0
def render_html_to_pdf(html, filename):
    pisa.showLogging()
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), file(filename, "wb"))
    if pdf.err:
        print "Error: " + pdf.err