How to use the xhtml2pdf.pisa function in xhtml2pdf

To help you get started, we’ve selected a few xhtml2pdf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xhtml2pdf / xhtml2pdf / testrender / testrender.py View on Github external
def render_pdf(filename, output_dir, options):
    if options.debug:
        print('Rendering %s' % filename)
    basename = os.path.basename(filename)
    outname = '%s.pdf' % os.path.splitext(basename)[0]
    outfile = os.path.join(output_dir, outname)

    input = open(filename, 'rb')
    output = open(outfile, 'wb')

    result = pisa.pisaDocument(input, output, path=filename)

    input.close()
    output.close()

    if result.err:
        print('Error rendering %s: %s' % (filename, result.err))
        sys.exit(1)
    return outfile
github xhtml2pdf / xhtml2pdf / test / simple.py View on Github external
# 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 xhtml2pdf.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"):

    """
    Simple test showing how to create a PDF file from
github xhtml2pdf / xhtml2pdf / test / cookbook.py View on Github external
def HTML2PDF(data, filename, open=False):

    """
    Simple test showing how to create a PDF file from
    PML Source String. Also shows errors and tries to start
    the resulting PDF
    """

    pdf = pisa.CreatePDF(
        io.StringIO(data),
        file(filename, "wb"))

    if open and (not pdf.err):
        pisa.startViewer(filename)

    return not pdf.err
github dimagi / commcare-hq / custom / icds_reports / utils.py View on Github external
def create_pdf_file(pdf_hash, pdf_context):
    template = get_template("icds_reports/icds_app/pdf/issnip_monthly_register.html")
    resultFile = cStringIO()
    client = get_redis_client()
    try:
        pdf_page = template.render(pdf_context)
    except Exception as ex:
        pdf_page = str(ex)
    pisa.CreatePDF(
        pdf_page,
        dest=resultFile,
        show_error_as_pdf=True)
    client.set(pdf_hash, resultFile.getvalue())
    client.expire(pdf_hash, 24 * 60 * 60)
    resultFile.close()
    return pdf_hash
github NetAngels / django-webodt / webodt / converters / xhtml2pdf_converter.py View on Github external
def convert(self, document, format=None, output_filename=None, delete_on_close=True):
        if document.format != 'html':
            raise ConverterError(u'xhtml2pdf does not support %s input format' % document.format)
        if format != 'pdf':
            raise ConverterError(u'xhtml2pdf does not support %s output format' % format)
        output_filename, format = guess_format_and_filename(output_filename, format)
        input_file = document
        input_filename = document.name
        output_file = open(output_filename, 'wb')

        result = pisa.pisaDocument(
            input_file, output_file, path=input_filename, encoding='UTF-8',
        )

        output_file.close()

        if result.err:
            err_msg = 'Error rendering %s: %s' % (input_filename, result.err)
            raise ConverterError(err_msg)
        fd = Document(output_filename, mode='rb', delete_on_close=delete_on_close)
        return fd
github cedrick-f / pySequence / src / file2bmp.py View on Github external
def html2imgfile(nf , defaut = wx.NullBitmap, ext = ".png"):
    with open(nf,'r', encoding='utf-8') as f:
        sourceHtml = f.read()
        
    with tempfile.NamedTemporaryFile() as resultFile:
#     with open(nomFichierPDF, "w+b") as resultFile:
        try:
            pisaStatus = pisa.CreatePDF(sourceHtml,                # the HTML to convert
                                        dest=resultFile,
                                        show_error_as_pdf = True)           # file handle to recieve result
            return pdf2imgfile(resultFile.name, defaut)
        except:
            return defaut
github SasView / sasview / src / sas / sasgui / guiframe / report_dialog.py View on Github external
def HTML2PDF(self, data, filename):
        """
        Create a PDF file from html source string.
        Returns True is the file creation was successful.
        : data: html string
        : filename: name of file to be saved
        """
        try:
            from xhtml2pdf import pisa
            # open output file for writing (truncated binary)
            resultFile = open(filename, "w+b")
            # convert HTML to PDF
            pisaStatus = pisa.CreatePDF(data, dest=resultFile)
            # close output file
            resultFile.close()
            self.Update()
            return pisaStatus.err
        except Exception as exc:
            logger.error("Error creating pdf: %s" % exc)
        return False
github dimagi / commcare-hq / custom / icds_reports / utils / __init__.py View on Github external
def create_pdf_file(pdf_context):
    pdf_hash = uuid.uuid4().hex
    template = get_template("icds_reports/icds_app/pdf/issnip_monthly_register.html")
    resultFile = BytesIO()
    icds_file = IcdsFile(blob_id=pdf_hash, data_type='issnip_monthly')
    try:
        pdf_page = template.render(pdf_context)
    except Exception as ex:
        pdf_page = str(ex)
    pisa.CreatePDF(
        pdf_page,
        dest=resultFile,
        show_error_as_pdf=True)
    # we need to reset buffer position to the beginning after creating pdf, if not read() will return empty string
    # we read this to save file in blobdb
    resultFile.seek(0)

    icds_file.store_file_in_blobdb(resultFile, expired=60 * 60 * 24)
    icds_file.save()
    return pdf_hash
github renatoliveira / notto / notto / nottoapp / pdf_builder.py View on Github external
def render_to_pdf(template_src, context_dict):
    """
    renders a document to pdf using a template
    """
    if context_dict is None:
        context_dict = {}
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result,
                            encoding='UTF-8')
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None
github imtapps / django-response-helpers / response_helpers / helpers.py View on Github external
def get_pdf_stream(template_name, context):
    # don't import until you really have to so people using this don't need
    # to install xhtml2pdf and all its dependencies if they don't use it.
    from xhtml2pdf import pisa

    pdf_stream = StringIO()
    rendered_template = render_to_string(template_name, context)
    logger = logging.getLogger('response_helpers')
    logger.debug(rendered_template)

    pisa_document = pisa.pisaDocument(StringIO(rendered_template.encode("UTF-16")), pdf_stream)
    if pisa_document.err:
        exception_message = "Error creating pdf from html. \r\n"
        exception_message += "\r\n".join([str(msg) for msg in pisa_document.log])
        raise Exception(exception_message)

    return pdf_stream