Python pdfkit.from_file() Examples

The following are 14 code examples of pdfkit.from_file(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pdfkit , or try the search function .
Example #1
Source File: action.py    From insightconnect-plugins with MIT License 8 votes vote down vote up
def makePDF(html,path):
    infile = path+"str.html"
    outfile = path+"tmp.pdf"
    with open(infile,'w') as f:
        f.write(html)
    pdfkit.from_file(infile, outfile)
    outbytes = ""
    with open(outfile, 'r') as f:
        outbytes = f.read()
    return outbytes 
Example #2
Source File: report_helper.py    From OpenMF with Apache License 2.0 6 votes vote down vote up
def generate_pdf_report(session_name):
    html_filepath = generate_html_report(session_name)
    return pdfkit.from_file(html_filepath, ROOT_DIR + SEP + session_name + SEP + 'report' + SEP + 'report.pdf') 
Example #3
Source File: reports_panel.py    From mmvt with GNU General Public License v3.0 6 votes vote down vote up
def create_report():
    report_text = read_report_html()
    fields = parse_report_fields_from_text(report_text)
    for field in fields:
        report_text = report_text.replace(
            '~{}~'.format(field), ReportsPanel.fields_values[bpy.context.scene.reports_files][field])
    new_html_fname = op.join(_addon().get_output_path(), '{}.html'.format(
        bpy.context.scene.reports_files.replace(' ', '_')))
    with open(new_html_fname, 'w') as html_file:
        html_file.write(report_text)
    output_fname = mu.change_fname_extension(new_html_fname, 'pdf')
    pdfkit.from_file(new_html_fname, output_fname)
    try:
        import webbrowser
        webbrowser.open_new(output_fname)
    except:
        print('The new report can be found here: {}'.format(output_fname))
        pass 
Example #4
Source File: download.py    From spider with MIT License 6 votes vote down vote up
def download(links):
    num = 1
    for i in links:
        xtm = requests.get(url = 'http://www.hzcourse.com/resource/readBook?path=' + str(i),headers=headers)
        soup = BeautifulSoup(xtm.text,'lxml')
        for img in soup.find_all('img'):
            img['src'] = 'http://www.hzcourse.com/resource/readBook?path=/openresources/teach_ebook/uncompressed/18563/OEBPS/Text/' + img['src']
        article = str(soup).encode('utf-8')
        with open(str(num) + '.html','wb') as f:
            f.write(article)
            f.close()
        try:
            pdfkit.from_file(str(num) + '.html',str(num) + '.pdf',configuration=config,options=options)
        except Exception as e:
            print('Error for ' + str(e) + ',Page :' + str(num))
        num += 1
        sleep(1) 
Example #5
Source File: htmltopdf.py    From Jarvis with MIT License 5 votes vote down vote up
def __call__(self, jarvis, s):
        if not s:
            jarvis.say("please enter a file name after calling the plugin")
        elif "html" not in s:
            jarvis.say("Your file must end with '.html'")
        else:
            try:
                pdfkit.from_file(s, s.replace('.html', '') + '.pdf')
            except OSError as err:
                jarvis.say("OS error: {0}".format(err) + "\nMake sur your file is in the source directory of Jarvis and is an html file") 
Example #6
Source File: liaoxuefeng_pdf.py    From crawler with MIT License 5 votes vote down vote up
def save_pdf(htmls, file_name):

    options = {

        'page-size': 'Letter',

        'margin-top': '0.75in',

        'margin-right': '0.75in',

        'margin-bottom': '0.75in',

        'margin-left': '0.75in',

        'encoding': "UTF-8",

        'custom-header': [

            ('Accept-Encoding', 'gzip')

        ],

        'cookie': [

            ('cookie-name1', 'cookie-value1'),

            ('cookie-name2', 'cookie-value2'),

        ],

        'outline-depth': 10,

    }

    pdfkit.from_file(htmls, file_name, options=options) 
Example #7
Source File: logic.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def _call_pdfkit(self, html_file, uuid_directory_name, uuid_file_name):
        """ Runs wkhtmltopdf to create a PDF file.

        :param html_file: the input HTML
        :param uuid_directory_name: the temporary directory on which we are working
        :param uuid_file_name: the XML UUID file name from which the HTML was derived
        :return: the output file path
        """
        pdfkit_options = {
            'margin-top': '0',
            'margin-right': '0',
            'margin-bottom': '0',
            'margin-left': '0',
            'encoding': 'UTF-8',
            'javascript-delay': '9000',
            'no-stop-slow-scripts': '',
        }

        pdfkit_config = pdfkit.configuration(
            wkhtmltopdf=bytes(os.path.join(self.current_path, 'cassius/' 'bin', 'wkhtmltopdf'), 'utf-8')
        )

        pdfkit_output_file = '{0}.pdf'.format(os.path.join(uuid_directory_name, uuid_file_name))

        pdfkit.from_file(html_file, pdfkit_output_file, options=pdfkit_options, configuration=pdfkit_config)

        return pdfkit_output_file 
Example #8
Source File: Common.py    From RENAT with Apache License 2.0 5 votes vote down vote up
def convert_html_to_pdf(html_file,pdf_file):
    """ Converts html file to pdf file
    """
    options = {
        'page-size': 'A4',
        'margin-top': '0.1in',
        'margin-right': '0.1in',
        'margin-bottom': '0.1in',
        'margin-left': '0.1in',
        'encoding': "UTF-8",
        'no-outline': None
    }
    pdfkit.from_file(html_file,pdf_file,options)
    BuiltIn().log("Converted `%s` to `%s`" % (html_file,pdf_file)) 
Example #9
Source File: crawl.py    From crawl-zsxq with MIT License 5 votes vote down vote up
def make_pdf(htmls):
    html_files = []
    for index, html in enumerate(htmls):
        file = str(index) + ".html"
        html_files.append(file)
        with open(file, "w", encoding="utf-8") as f:
            f.write(html)

    options = {
        "user-style-sheet": "test.css",
        "page-size": "Letter",
        "margin-top": "0.75in",
        "margin-right": "0.75in",
        "margin-bottom": "0.75in",
        "margin-left": "0.75in",
        "encoding": "UTF-8",
        "custom-header": [("Accept-Encoding", "gzip")],
        "cookie": [
            ("cookie-name1", "cookie-value1"), ("cookie-name2", "cookie-value2")
        ],
        "outline-depth": 10,
    }
    try:
        pdfkit.from_file(html_files, "电子书.pdf", options=options)
    except Exception as e:
        pass

    for file in html_files:
        os.remove(file)

    print("已制作电子书在当前目录!") 
Example #10
Source File: report.py    From vaxrank with Apache License 2.0 5 votes vote down vote up
def make_pdf_report(
        template_data,
        pdf_report_path):
    with tempfile.NamedTemporaryFile(mode='w', suffix='.html') as f:
        _make_report(template_data, f, 'templates/template.html')
        f.flush()

        options = {
            'zoom': 0.55,
            'margin-top': '20mm'
        }

        if sys.platform in ('linux', 'linux2'):
            # pdfkit uses wkhtmltopdf, which doesn't work on headless servers;
            # recommended workaround is to use xvfb, as documented here:
            # https://github.com/wkhtmltopdf/wkhtmltopdf/issues/2037#issuecomment-62019521
            from xvfbwrapper import Xvfb
            logger.info('Running pdfkit inside xvfb wrapper')
            with Xvfb():
                pdfkit.from_file(f.name, pdf_report_path, options=options)

        else:
            pdfkit.from_file(f.name, pdf_report_path, options=options)
    logger.info('Wrote PDF report to %s', pdf_report_path) 
Example #11
Source File: html_report.py    From treeomics with GNU General Public License v3.0 5 votes vote down vote up
def create_pdf(self):
        """
        Convert HTML report to PDF
        """

        try:  # check if varcode and pyensembl is available (necessary for Windows)
            import pdfkit

        except ImportError:
            logger.warning('PDFKIT not available and hence no PDF of the HTML report was created.')
            return

        pdf_filepath = self.filepath.replace('.html', '.pdf')

        options = {
            'zoom': settings.ZOOM,
            'dpi': 400,
            # 'print-media-type': '',
            'page-size': 'Letter',
            'margin-top': '1in',
            'margin-right': '0.75in',
            'margin-bottom': '1in',
            'margin-left': '0.75in',
            'disable-smart-shrinking': '',
            'quiet': ''

            # 'encoding': "UTF-8",
            # 'custom-header': [
            #     ('Accept-Encoding', 'gzip')
            # ]
            # 'cookie': [
            #     ('cookie-name1', 'cookie-value1'),
            #     ('cookie-name2', 'cookie-value2'),
            # ],
            # 'no-outline': None
        }

        pdfkit.from_file(self.filepath, pdf_filepath, options=options) 
Example #12
Source File: create_report.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def create_pdf(html_fname, pdf_fname):
    pdfkit.from_file(html_fname, pdf_fname) 
Example #13
Source File: crawl.py    From zsxq-spider with MIT License 5 votes vote down vote up
def make_pdf(htmls):
    html_files = []
    for index, html in enumerate(htmls):
        file = str(index) + ".html"
        html_files.append(file)
        with open(file, "w", encoding="utf-8") as f:
            f.write(html)

    options = {
        "user-style-sheet": "temp.css",
        "page-size": "Letter",
        "margin-top": "0.75in",
        "margin-right": "0.75in",
        "margin-bottom": "0.75in",
        "margin-left": "0.75in",
        "encoding": "UTF-8",
        "custom-header": [("Accept-Encoding", "gzip")],
        "cookie": [
            ("cookie-name1", "cookie-value1"), ("cookie-name2", "cookie-value2")
        ],
        "outline-depth": 10,
    }
    try:
        pdfkit.from_file(html_files, PDF_FILE_NAME, options=options)
    except Exception as e:
        pass

    if DELETE_HTML_WHEN_DONE:
        for file in html_files:
            os.remove(file)

    print("电子书生成成功!") 
Example #14
Source File: html_to_pdf.py    From python-tools with MIT License 4 votes vote down vote up
def html_to_pdf(input, output, type='string'):
    """Convert HTML/webpage to PDF. For linux, install: sudo apt-get install wkhtmltopdf.

    Args:
        input (str): HTML Text, URL or file.
        output (str): Output file (.pdf).
        type (str): Types can be 'string', 'url' or 'file'.

    """
    if type == 'url':
        pdfkit.from_url(input, output)
    elif type == 'file':
        pdfkit.from_file(input, output)
    else:
        pdfkit.from_string(input, output)