1
1
mirror of https://github.com/Kozea/WeasyPrint.git synced 2024-10-05 08:27:22 +03:00
WeasyPrint/weasyprint/__main__.py

209 lines
7.3 KiB
Python
Raw Normal View History

"""
weasyprint.__main__
-------------------
Command-line interface to WeasyPrint.
"""
import argparse
2017-03-25 01:12:04 +03:00
import logging
2020-01-11 20:33:59 +03:00
import platform
2017-03-25 02:33:36 +03:00
import sys
import cairosvg
import pydyf
2020-05-30 02:27:13 +03:00
from . import HTML, LOGGER, __version__
from .text import pango
class PrintInfo(argparse.Action):
def __call__(*_, **__):
2020-01-11 20:33:59 +03:00
uname = platform.uname()
print('System:', uname.system)
print('Machine:', uname.machine)
print('Version:', uname.version)
print('Release:', uname.release)
print()
2020-05-30 02:27:13 +03:00
print('WeasyPrint version:', __version__)
print('Python version:', sys.version.split()[0])
print('Pydyf version:', pydyf.__version__)
print('Pango version:', pango.pango_version())
print('CairoSVG version:', cairosvg.__version__)
sys.exit()
2012-06-02 08:28:44 +04:00
def main(argv=None, stdout=None, stdin=None):
2012-10-08 21:51:18 +04:00
"""The ``weasyprint`` program takes at least two arguments:
.. code-block:: sh
weasyprint [options] <input> <output>
The input is a filename or URL to an HTML document, or ``-`` to read
HTML from stdin. The output is a filename, or ``-`` to write to stdout.
Options can be mixed anywhere before, between, or after the input and
output.
.. option:: -e <input_encoding>, --encoding <input_encoding>
Force the input character encoding (e.g. ``-e utf8``).
.. option:: -f <output_format>, --format <output_format>
Choose the output file format among PDF and PNG (e.g. ``-f png``).
Required if the output is not a ``.pdf`` or ``.png`` filename.
.. option:: -s <filename_or_URL>, --stylesheet <filename_or_URL>
Filename or URL of a user cascading stylesheet (see
:ref:`stylesheet-origins`) to add to the document
(e.g. ``-s print.css``). Multiple stylesheets are allowed.
.. option:: -m <type>, --media-type <type>
Set the media type to use for ``@media``. Defaults to ``print``.
.. option:: -r <dpi>, --resolution <dpi>
For PNG output only. Set the resolution in PNG pixel per CSS inch.
Defaults to 96, which means that PNG pixels match CSS pixels.
.. option:: -u <URL>, --base-url <URL>
Set the base for relative URLs in the HTML input.
Defaults to the inputs own URL, or the current directory for stdin.
2014-04-04 14:32:21 +04:00
.. option:: -a <file>, --attachment <file>
Adds an attachment to the document. The attachment is
included in the PDF output. This option can be used multiple
times.
2014-04-04 14:32:21 +04:00
2016-08-30 19:15:30 +03:00
.. option:: -p, --presentational-hints
Follow `HTML presentational hints
<https://www.w3.org/TR/html/rendering.html\
#the-css-user-agent-style-sheet-and-presentational-hints>`_.
2016-08-30 19:15:30 +03:00
.. option:: -v, --verbose
Show warnings and information messages.
.. option:: -d, --debug
Show debugging messages.
.. option:: --version
2012-10-08 21:51:18 +04:00
Show the version number. Other options and arguments are ignored.
.. option:: -h, --help
2012-10-08 21:51:18 +04:00
Show the command-line usage. Other options and arguments are ignored.
"""
2013-04-11 14:08:53 +04:00
parser = argparse.ArgumentParser(
prog='weasyprint', description='Renders web pages to PDF or PNG.')
parser.add_argument('--version', action='version',
2020-05-30 02:27:13 +03:00
version=f'WeasyPrint version {__version__}',
2013-10-14 18:07:05 +04:00
help="Print WeasyPrint's version number and exit.")
parser.add_argument('-i', '--info', action=PrintInfo, nargs=0,
help='Print system information and exit.')
parser.add_argument('-e', '--encoding',
help='Character encoding of the input')
parser.add_argument('-f', '--format', choices=['pdf', 'png'],
2017-01-16 03:55:12 +03:00
help='Output format. Can be omitted if `output` '
'ends with a .pdf or .png extension.')
parser.add_argument('-s', '--stylesheet', action='append',
help='URL or filename for a user CSS stylesheet. '
'May be given multiple times.')
parser.add_argument('-m', '--media-type', default='print',
help='Media type to use for @media, defaults to print')
parser.add_argument('-r', '--resolution', type=float,
help='PNG only: the resolution in pixel per CSS inch. '
'Defaults to 96, one PNG pixel per CSS pixel.')
parser.add_argument('-u', '--base-url',
help='Base for relative URLs in the HTML input. '
"Defaults to the input's own filename or URL "
'or the current directory for stdin.')
2014-04-04 14:32:21 +04:00
parser.add_argument('-a', '--attachment', action='append',
2014-04-27 21:16:14 +04:00
help='URL or filename of a file '
'to attach to the PDF document')
2016-08-30 19:15:30 +03:00
parser.add_argument('-p', '--presentational-hints', action='store_true',
help='Follow HTML presentational hints.')
2017-07-25 15:00:35 +03:00
parser.add_argument('-v', '--verbose', action='store_true',
help='Show warnings and information messages.')
parser.add_argument('-d', '--debug', action='store_true',
help='Show debugging messages.')
parser.add_argument('-q', '--quiet', action='store_true',
help='Hide logging messages.')
2013-04-11 14:08:53 +04:00
parser.add_argument(
'input', help='URL or filename of the HTML input, or - for stdin')
parser.add_argument(
'output', help='Filename where output is written, or - for stdout')
args = parser.parse_args(argv)
if args.format is None:
2012-02-29 23:17:44 +04:00
output_lower = args.output.lower()
if output_lower.endswith('.pdf'):
format_ = 'pdf'
elif output_lower.endswith('.png'):
format_ = 'png'
else:
parser.error(
2017-01-16 03:55:12 +03:00
'Either specify a format with -f or choose an '
'output filename that ends in .pdf or .png')
else:
2012-02-29 23:17:44 +04:00
format_ = args.format.lower()
if args.input == '-':
2020-01-11 20:33:59 +03:00
source = stdin or sys.stdin.buffer
if args.base_url is None:
args.base_url = '.' # current directory
elif args.base_url == '':
args.base_url = None # no base URL
else:
source = args.input
if args.output == '-':
2020-01-11 20:33:59 +03:00
output = stdout or sys.stdout.buffer
else:
output = args.output
kwargs = {
'stylesheets': args.stylesheet,
'presentational_hints': args.presentational_hints}
if args.resolution:
if format_ == 'png':
kwargs['resolution'] = args.resolution
else:
parser.error('--resolution only applies for the PNG format.')
2014-04-04 14:32:21 +04:00
if args.attachment:
if format_ == 'pdf':
kwargs['attachments'] = args.attachment
2014-04-04 14:32:21 +04:00
else:
parser.error('--attachment only applies for the PDF format.')
2017-03-25 01:12:04 +03:00
# Default to logging to stderr.
if args.debug:
LOGGER.setLevel(logging.DEBUG)
elif args.verbose:
LOGGER.setLevel(logging.INFO)
if not args.quiet:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
LOGGER.addHandler(handler)
2017-03-25 01:12:04 +03:00
html = HTML(source, base_url=args.base_url, encoding=args.encoding,
media_type=args.media_type)
getattr(html, 'write_' + format_)(output, **kwargs)
2012-04-02 16:45:44 +04:00
if __name__ == '__main__': # pragma: no cover
2012-02-17 18:00:55 +04:00
main()