Repository: Kozea/WeasyPrint
Pull request #1860 (2023-04-13 17:38:20)

Use dictionary to store API options
This commit uses an "option" dictionary to store various API options that were used as arguments in many public and private functions. This change allows to easily document default values, to reduce the number of arguments and to avoid many repetitions in documentation and signatures.

The changes to the public API are minimal, and should only have an impact for users who passed unnamed arguments.


Patch:
diff --git a/docs/api_reference.rst b/docs/api_reference.rst
index 9c60c158..69907152 100644
--- a/docs/api_reference.rst
+++ b/docs/api_reference.rst
@@ -57,6 +57,7 @@ Python API
 .. autoclass:: CSS(input, **kwargs)
 .. autoclass:: Attachment(input, **kwargs)
 .. autofunction:: default_url_fetcher
+.. autodata:: DEFAULT_OPTIONS
 
 .. module:: weasyprint.document
 .. autoclass:: Document
diff --git a/weasyprint/__init__.py b/weasyprint/__init__.py
index ce6351fa..8cd2c9ed 100644
--- a/weasyprint/__init__.py
+++ b/weasyprint/__init__.py
@@ -15,9 +15,71 @@ import tinycss2
 
 VERSION = __version__ = '58.1'
 
+#: Default values for command-line and Python API options. See
+#: :func:`__main__.main` to learn more about specific options for
+#: command-line.
+#:
+#: :param list stylesheets:
+#:     An optional list of user stylesheets. The list can include
+#:     are :class:`CSS` objects, filenames, URLs, or file-like
+#:     objects. (See :ref:`Stylesheet Origins`.)
+#: :param str media_type:
+#:     Media type to use for @media.
+#: :param list attachments:
+#:     A list of additional file attachments for the generated PDF
+#:     document or :obj:`None`. The list's elements are
+#:     :class:`Attachment` objects, filenames, URLs or file-like objects.
+#: :param bytes pdf_identifier:
+#:     A bytestring used as PDF file identifier.
+#: :param str pdf_variant:
+#:     A PDF variant name.
+#: :param str pdf_version:
+#:     A PDF version number.
+#: :param bool pdf_forms:
+#:     Whether PDF forms have to be included.
+#: :param bool uncompressed_pdf:
+#:     Whether PDF content should be compressed.
+#: :param bool custom_metadata:
+#:     Whether custom HTML metadata should be stored in the generated PDF.
+#: :param bool presentational_hints:
+#:     Whether HTML presentational hints are followed.
+#: :param bool optimize_images:
+#:     Whether size of embedded images should be optimized, with no quality
+#:     loss.
+#: :param int jpeg_quality:
+#:     JPEG quality between 0 (worst) to 95 (best).
+#: :param int dpi:
+#:     Maximum resolution of images embedded in the PDF.
+#: :param bool full_fonts:
+#:     Whether unmodified font files should be embedded when possible.
+#: :param bool hinting:
+#:     Whether hinting information should be kept in embedded fonts.
+#: :type image_cache: :obj:`dict` or :obj:`str`
+#: :param cache_folder:
+#:     A dictionary used to cache images, or a folder path where images
+#:     are temporarily stored.
+DEFAULT_OPTIONS = {
+    'stylesheets': None,
+    'media_type': 'print',
+    'attachments': None,
+    'pdf_identifier': None,
+    'pdf_variant': None,
+    'pdf_version': None,
+    'pdf_forms': None,
+    'uncompressed_pdf': False,
+    'custom_metadata': False,
+    'presentational_hints': False,
+    'optimize_images': False,
+    'jpeg_quality': None,
+    'dpi': None,
+    'full_fonts': False,
+    'hinting': False,
+    'cache_folder': None,
+}
+
 __all__ = [
-    'HTML', 'CSS', 'Attachment', 'Document', 'Page', 'default_url_fetcher',
-    'VERSION', '__version__']
+    'HTML', 'CSS', 'DEFAULT_OPTIONS', 'Attachment', 'Document', 'Page',
+    'default_url_fetcher', 'VERSION', '__version__']
 
 
 # Import after setting the version, as the version is used in other modules
@@ -53,12 +115,15 @@ class HTML:
     Alternatively, use **one** named argument so that no guessing is involved:
 
     :type filename: str or pathlib.Path
-    :param filename: A filename, relative to the current directory, or
-        absolute.
-    :param str url: An absolute, fully qualified URL.
+    :param filename:
+        A filename, relative to the current directory, or absolute.
+    :param str url:
+        An absolute, fully qualified URL.
     :type file_obj: :term:`file object`
-    :param file_obj: Any object with a ``read`` method.
-    :param str string: A string of HTML source.
+    :param file_obj:
+        Any object with a ``read`` method.
+    :param str string:
+        A string of HTML source.
 
     Specifying multiple inputs is an error:
     ``HTML(filename="foo.html", url="localhost://bar.html")``
@@ -66,20 +131,22 @@ class HTML:
 
     You can also pass optional named arguments:
 
-    :param str encoding: Force the source character encoding.
-    :param str base_url: The base used to resolve relative URLs
-        (e.g. in ``<img src="../foo.png">``). If not provided, try to use
-        the input filename, URL, or ``name`` attribute of :term:`file objects
-        <file object>`.
-    :type url_fetcher: :term:`function`
-    :param url_fetcher: A function or other callable
-        with the same signature as :func:`default_url_fetcher` called to
-        fetch external resources such as stylesheets and images.
-        (See :ref:`URL Fetchers`.)
-    :param str media_type: The media type to use for ``@media``.
-        Defaults to ``'print'``. **Note:** In some cases like
-        ``HTML(string=foo)`` relative URLs will be invalid if ``base_url``
-        is not provided.
+    :param str encoding:
+        Force the source character encoding.
+    :param str base_url:
+        The base used to resolve relative URLs (e.g. in
+        ``<img src="../foo.png">``). If not provided, try to use the input
+        filename, URL, or ``name`` attribute of
+        :term:`file objects <file object>`.
+    :type url_fetcher: :term:`callable`
+    :param url_fetcher:
+        A function or other callable with the same signature as
+        :func:`default_url_fetcher` called to fetch external resources such as
+        stylesheets and images. (See :ref:`URL Fetchers`.)
+    :param str media_type:
+        The media type to use for ``@media``. Defaults to ``'print'``.
+        **Note:** In some cases like ``HTML(string=foo)`` relative URLs will be
+        invalid if ``base_url`` is not provided.
 
     """
     def __init__(self, guess=None, filename=None, url=None, file_obj=None,
@@ -117,49 +184,32 @@ class HTML:
     def _ph_stylesheets(self):
         return [HTML5_PH_STYLESHEET]
 
-    def render(self, stylesheets=None, presentational_hints=False,
-               optimize_size=('fonts', 'hinting', 'pdf'), jpeg_quality=None,
-               dpi=None, font_config=None, counter_style=None,
-               image_cache=None, forms=False):
+    def render(self, font_config=None, counter_style=None, **options):
         """Lay out and paginate the document, but do not (yet) export it.
 
         This returns a :class:`document.Document` object which provides
         access to individual pages and various meta-data.
         See :meth:`write_pdf` to get a PDF directly.
 
-        :param list stylesheets:
-            An optional list of user stylesheets. List elements are
-            :class:`CSS` objects, filenames, URLs, or file
-            objects. (See :ref:`Stylesheet Origins`.)
-        :param bool presentational_hints:
-            Whether HTML presentational hints are followed.
-        :param tuple optimize_size:
-            Optimize size of generated PDF. Can contain "images", "fonts",
-            "hinting" and "pdf".
-        :param int jpeg_quality: JPEG quality between 0 (worst) to 95 (best).
-        :param int dpi: Maximum resolution of images embedded in the PDF.
         :type font_config: :class:`text.fonts.FontConfiguration`
-        :param font_config: A font configuration handling ``@font-face`` rules.
+        :param font_config:
+            A font configuration handling ``@font-face`` rules.
         :type counter_style: :class:`css.counters.CounterStyle`
-        :param counter_style: A dictionary storing ``@counter-style`` rules.
-        :param image_cache:
-            A dictionary used to cache images, or a folder path where images
-            are temporarily stored.
-        :type image_cache: :obj:`dict` or :obj:`str`
-        :param bool forms: Whether PDF forms have to be included.
+        :param counter_style:
+            A dictionary storing ``@counter-style`` rules.
+        :param options:
+            The ``options`` parameter includes by default the
+            :data:`DEFAULT_OPTIONS` values.
         :returns: A :class:`document.Document` object.
 
         """
-        return Document._render(
-            self, stylesheets, presentational_hints, optimize_size,
-            jpeg_quality, dpi, font_config, counter_style, image_cache, forms)
-
-    def write_pdf(self, target=None, stylesheets=None, zoom=1,
-                  attachments=None, finisher=None, presentational_hints=False,
-                  optimize_size=('fonts', 'hinting', 'pdf'), jpeg_quality=None,
-                  dpi=None, font_config=None, counter_style=None,
-                  image_cache=None, identifier=None, variant=None,
-                  version=None, forms=False, custom_metadata=False):
+        new_options = DEFAULT_OPTIONS.copy()
+        new_options.update(options)
+        options = new_options
+        return Document._render(self, font_config, counter_style, options)
+
+    def write_pdf(self, target=None, zoom=1, finisher=None,
+                  font_config=None, counter_style=None, **options):
         """Render the document to a PDF file.
 
         This is a shortcut for calling :meth:`render`, then
@@ -170,55 +220,37 @@ class HTML:
         :param target:
             A filename where the PDF file is generated, a file object, or
             :obj:`None`.
-        :param list stylesheets:
-            An optional list of user stylesheets. The list's elements
-            are :class:`CSS` objects, filenames, URLs, or file-like
-            objects. (See :ref:`Stylesheet Origins`.)
         :param float zoom:
             The zoom factor in PDF units per CSS units.  **Warning**:
             All CSS units are affected, including physical units like
             ``cm`` and named sizes like ``A4``.  For values other than
             1, the physical CSS units will thus be "wrong".
-        :param list attachments: A list of additional file attachments for the
-            generated PDF document or :obj:`None`. The list's elements are
-            :class:`Attachment` objects, filenames, URLs or file-like objects.
-        :param finisher: A finisher function, that accepts the document and a
-            :class:`pydyf.PDF` object as parameters, can be passed to perform
+        :type finisher: :term:`callable`
+        :param finisher:
+            A finisher function or callable that accepts the document and a
+            :class:`pydyf.PDF` object as parameters. Can be passed to perform
             post-processing on the PDF right before the trailer is written.
-        :param bool presentational_hints: Whether HTML presentational hints are
-            followed.
-        :param tuple optimize_size:
-            Optimize size of generated PDF. Can contain "images", "fonts",
-            "hinting" and "pdf".
-        :param int jpeg_quality: JPEG quality between 0 (worst) to 95 (best).
-        :param int dpi: Maximum resolution of images embedded in the PDF.
         :type font_config: :class:`text.fonts.FontConfiguration`
-        :param font_config: A font configuration handling ``@font-face`` rules.
+        :param font_config:
+            A font configuration handling ``@font-face`` rules.
         :type counter_style: :class:`css.counters.CounterStyle`
-        :param counter_style: A dictionary storing ``@counter-style`` rules.
-        :param image_cache:
-            A dictionary used to cache images, or a folder path where images
-            are temporarily stored.
-        :type image_cache: :obj:`dict` or :obj:`str`
-        :param bytes identifier: A bytestring used as PDF file identifier.
-        :param str variant: A PDF variant name.
-        :param str version: A PDF version number.
-        :param bool forms: Whether PDF forms have to be included.
-        :param bool custom_metadata: Whether custom HTML metadata should be
-            stored in the generated PDF.
+        :param counter_style:
+            A dictionary storing ``@counter-style`` rules.
+        :param options:
+            The ``options`` parameter includes by default the
+            :data:`DEFAULT_OPTIONS` values.
         :returns:
             The PDF as :obj:`bytes` if ``target`` is not provided or
             :obj:`None`, otherwise :obj:`None` (the PDF is written to
             ``target``).
 
         """
+        new_options = DEFAULT_OPTIONS.copy()
+        new_options.update(options)
+        options = new_options
         return (
-            self.render(
-                stylesheets, presentational_hints, optimize_size, jpeg_quality,
-                dpi, font_config, counter_style, image_cache, forms)
-            .write_pdf(
-                target, zoom, attachments, finisher, identifier, variant,
-                version, custom_metadata))
+            self.render(font_config, counter_style, **options)
+            .write_pdf(target, zoom, finisher, **options))
 
 
 class CSS:
@@ -274,8 +306,9 @@ class Attachment:
     supported. An optional description can be provided with the ``description``
     argument.
 
-    :param description: A description of the attachment to be included in the
-        PDF document. May be :obj:`None`.
+    :param description:
+        A description of the attachment to be included in the PDF document.
+        May be :obj:`None`.
 
     """
     def __init__(self, guess=None, filename=None, url=None, file_obj=None,
diff --git a/weasyprint/__main__.py b/weasyprint/__main__.py
index aef713d8..47e04070 100644
--- a/weasyprint/__main__.py
+++ b/weasyprint/__main__.py
@@ -4,10 +4,11 @@ import argparse
 import logging
 import platform
 import sys
+from warnings import warn
 
 import pydyf
 
-from . import HTML, LOGGER, __version__
+from . import DEFAULT_OPTIONS, HTML, LOGGER, __version__
 from .pdf import VARIANTS
 from .text.ffi import pango
 
@@ -27,173 +28,125 @@ class PrintInfo(argparse.Action):
         sys.exit()
 
 
-def main(argv=None, stdout=None, stdin=None):
+class Parser(argparse.ArgumentParser):
+    def __init__(self, *args, **kwargs):
+        self._arguments = {}
+        super().__init__(*args, **kwargs)
+
+    def add_argument(self, *args, **kwargs):
+        super().add_argument(*args, **kwargs)
+        key = args[-1].lstrip('-')
+        kwargs['flags'] = args
+        kwargs['positional'] = args[-1][0] != '-'
+        self._arguments[key] = kwargs
+
+    @property
+    def docstring(self):
+        self._arguments['help'] = self._arguments.pop('help')
+        data = []
+        for key, args in self._arguments.items():
+            data.append('.. option:: ')
+            action = args.get('action', 'store')
+            for flag in args['flags']:
+                data.append(flag)
+                if not args['positional'] and action in ('store', 'append'):
+                    data.append(f' <{key}>')
+                data.append(', ')
+            data[-1] = '\n\n'
+            data.append(f'  {args["help"][0].upper()}{args["help"][1:]}.\n\n')
+            if 'choices' in args:
+                choices = ", ".join(args['choices'])
+                data.append(f'  Possible choices: {choices}.\n\n')
+            if action == 'append':
+                data.append('  This option can be passed multiple times.\n\n')
+        return ''.join(data)
+
+
+PARSER = Parser(
+    prog='weasyprint', description='Render web pages to PDF.')
+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')
+PARSER.add_argument(
+    '-e', '--encoding', help='force the input character encoding')
+PARSER.add_argument(
+    '-s', '--stylesheet', action='append', dest='stylesheets',
+    help='URL or filename for a user CSS stylesheet')
+PARSER.add_argument(
+    '-m', '--media-type',
+    help='media type to use for @media, defaults to print')
+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')
+PARSER.add_argument(
+    '-a', '--attachment', action='append', dest='attachments',
+    help='URL or filename of a file to attach to the PDF document')
+PARSER.add_argument('--pdf-identifier', help='PDF file identifier')
+PARSER.add_argument(
+    '--pdf-variant', choices=VARIANTS, help='PDF variant to generate')
+PARSER.add_argument('--pdf-version', help='PDF version number')
+PARSER.add_argument(
+    '--pdf-forms', action='store_true', help='include PDF forms')
+PARSER.add_argument(
+    '--uncompressed-pdf', action='store_true',
+    help='do not compress PDF content, mainly for debugging purpose')
+PARSER.add_argument(
+    '--custom-metadata', action='store_true',
+    help='include custom HTML meta tags in PDF metadata')
+PARSER.add_argument(
+    '-p', '--presentational-hints', action='store_true',
+    help='follow HTML presentational hints')
+PARSER.add_argument(
+    '--optimize-images', action='store_true',
+    help='optimize size of embedded images with no quality loss')
+PARSER.add_argument(
+    '-j', '--jpeg-quality', type=int,
+    help='JPEG quality between 0 (worst) to 95 (best)')
+PARSER.add_argument(
+    '--full-fonts', action='store_true',
+    help='embed unmodified font files when possible')
+PARSER.add_argument(
+    '--hinting', action='store_true',
+    help='keep hinting information in embedded fonts')
+PARSER.add_argument(
+    '-c', '--cache-folder',
+    help='store cache on disk instead of memory, folder is '
+    'created if needed and cleaned after the PDF is generated')
+PARSER.add_argument(
+    '-D', '--dpi', type=int,
+    help='set maximum resolution of images embedded in the PDF')
+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')
+PARSER.add_argument(
+    '--version', action='version',
+    version=f'WeasyPrint version {__version__}',
+    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(
+    '-O', '--optimize-size', action='append',
+    help='deprecated, use other options instead',
+    choices=('images', 'fonts', 'hinting', 'pdf', 'all', 'none'))
+PARSER.set_defaults(**DEFAULT_OPTIONS)
+
+
+def main(argv=None, stdout=None, stdin=None, HTML=HTML):
     """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 utf-8``).
-
-    .. 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:: -u <URL>, --base-url <URL>
-
-        Set the base for relative URLs in the HTML input.
-        Defaults to the input’s own URL, or the current directory for stdin.
-
-    .. 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.
-
-    .. option:: --pdf-identifier <identifier>
-
-        PDF file identifier, used to check whether two different files
-        are two different versions of the same original document.
-
-    .. option:: --pdf-variant <variant-name>
-
-        PDF variant to generate (e.g. ``--pdf-variant pdf/a-3b``).
-
-    .. option:: --pdf-version <version-number>
-
-        PDF version number (default is 1.7).
-
-    .. option:: --custom-metadata
-
-        Include custom HTML meta tags in PDF metadata.
-
-    .. 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>`_.
-
-    .. option:: -O <type>, --optimize-size <type>
-
-        Optimize the size of generated documents. Supported types are
-        ``images``, ``fonts``, ``hinting``, ``pdf``, ``all`` and ``none``.
-        This option can be used multiple times, ``all`` adds all allowed
-        values, ``none`` removes all previously set values (including the
-        default ones, ``fonts`` and ``pdf``).
-
-    .. option:: -c <folder>, --cache-folder <folder>
-
-        Store cache on disk instead of memory. The ``folder`` is created if
-        needed and cleaned after the PDF is generated.
-
-    .. option:: -j <quality>, --jpeg-quality <quality>
-
-        JPEG quality between 0 (worst) to 95 (best).
-
-    .. option:: -D <dpi>, --dpi <dpi>
-
-        Maximum resolution of images embedded in the PDF.
-
-    .. option:: -v, --verbose
-
-        Show warnings and information messages.
-
-    .. option:: -d, --debug
-
-        Show debugging messages.
-
-    .. option:: -q, --quiet
-
-        Hide logging messages.
-
-    .. option:: --version
-
-        Show the version number. Other options and arguments are ignored.
-
-    .. option:: -h, --help
-
-        Show the command-line usage. Other options and arguments are ignored.
-
     """
-    parser = argparse.ArgumentParser(
-        prog='weasyprint', description='Render web pages to PDF.')
-    parser.add_argument(
-        '--version', action='version',
-        version=f'WeasyPrint version {__version__}',
-        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(
-        '-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(
-        '-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')
-    parser.add_argument(
-        '-a', '--attachment', action='append',
-        help='URL or filename of a file to attach to the PDF document')
-    parser.add_argument('--pdf-identifier', help='PDF file identifier')
-    parser.add_argument(
-        '--pdf-variant', choices=VARIANTS, help='PDF variant to generate')
-    parser.add_argument('--pdf-version', help='PDF version number')
-    parser.add_argument(
-        '--pdf-forms', action='store_true', help='Include PDF forms')
-    parser.add_argument(
-        '--custom-metadata', action='store_true',
-        help='include custom HTML meta tags in PDF metadata')
-    parser.add_argument(
-        '-p', '--presentational-hints', action='store_true',
-        help='follow HTML presentational hints')
-    parser.add_argument(
-        '-O', '--optimize-size', action='append',
-        help='optimize output size for specified features',
-        choices=('images', 'fonts', 'hinting', 'pdf', 'all', 'none'),
-        default=['fonts', 'hinting', 'pdf'])
-    parser.add_argument(
-        '-c', '--cache-folder',
-        help='Store cache on disk instead of memory. The ``folder`` is '
-        'created if needed and cleaned after the PDF is generated.')
-    parser.add_argument(
-        '-j', '--jpeg-quality', type=int,
-        help='JPEG quality between 0 (worst) to 95 (best)')
-    parser.add_argument(
-        '-D', '--dpi', type=int,
-        help='Maximum resolution of images embedded in the PDF')
-    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')
-    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)
+    args = PARSER.parse_args(argv)
 
     if args.input == '-':
         source = stdin or sys.stdin.buffer
@@ -209,29 +162,34 @@ def main(argv=None, stdout=None, stdin=None):
     else:
         output = args.output
 
-    optimize_size = set()
-    for arg in args.optimize_size:
-        if arg == 'none':
-            optimize_size.clear()
-        elif arg == 'all':
-            optimize_size |= {'images', 'fonts', 'hinting', 'pdf'}
-        else:
-            optimize_size.add(arg)
-
-    kwargs = {
-        'stylesheets': args.stylesheet,
-        'presentational_hints': args.presentational_hints,
-        'optimize_size': tuple(optimize_size),
-        'jpeg_quality': args.jpeg_quality,
-        'dpi': args.dpi,
-        'attachments': args.attachment,
-        'identifier': args.pdf_identifier,
-        'variant': args.pdf_variant,
-        'version': args.pdf_version,
-        'forms': args.pdf_forms,
-        'custom_metadata': args.custom_metadata,
-        'image_cache': args.cache_folder,
-    }
+    # TODO: to be removed when --optimize-size is removed
+    optimize_size = {'fonts', 'hinting', 'pdf'}
+    if args.optimize_size is not None:
+        warn(
+            'The --optimize-size option is now deprecated '
+            'and will be removed in next version. '
+            'Please use the other options available in --help instead.',
+            category=FutureWarning)
+        for arg in args.optimize_size:
+            if arg == 'none':
+                optimize_size.clear()
+            elif arg == 'all':
+                optimize_size |= {'images', 'fonts', 'hinting', 'pdf'}
+            else:
+                optimize_size.add(arg)
+    del args.optimize_size
+
+    options = vars(args)
+
+    # TODO: to be removed when --optimize-size is removed
+    if 'images' in optimize_size:
+        options['optimize_images'] = True
+    if 'fonts' not in optimize_size:
+        options['full_fonts'] = True
+    if 'hinting' not in optimize_size:
+        options['hinting'] = True
+    if 'pdf' not in optimize_size:
+        options['uncompressed_pdf'] = True
 
     # Default to logging to stderr.
     if args.debug:
@@ -246,7 +204,10 @@ def main(argv=None, stdout=None, stdin=None):
     html = HTML(
         source, base_url=args.base_url, encoding=args.encoding,
         media_type=args.media_type)
-    html.write_pdf(output, **kwargs)
+    html.write_pdf(output, **options)
+
+
+main.__doc__ += '\n\n' + PARSER.docstring
 
 
 if __name__ == '__main__':  # pragma: no cover
diff --git a/weasyprint/document.py b/weasyprint/document.py
index 74f78c74..dc0b07f9 100644
--- a/weasyprint/document.py
+++ b/weasyprint/document.py
@@ -5,7 +5,7 @@ import io
 from hashlib import md5
 from pathlib import Path
 
-from . import CSS
+from . import CSS, DEFAULT_OPTIONS
 from .anchors import gather_anchors, make_page_bookmark_tree
 from .css import get_all_computed_styles
 from .css.counters import CounterStyle
@@ -218,9 +218,7 @@ class Document:
     """
 
     @classmethod
-    def _build_layout_context(cls, html, stylesheets, presentational_hints,
-                              optimize_size, jpeg_quality, dpi, font_config,
-                              counter_style, image_cache, forms):
+    def _build_layout_context(cls, html, font_config, counter_style, options):
         if font_config is None:
             font_config = FontConfiguration()
         if counter_style is None:
@@ -228,23 +226,24 @@ class Document:
         target_collector = TargetCollector()
         page_rules = []
         user_stylesheets = []
-        if image_cache is None:
-            image_cache = {}
-        elif not isinstance(image_cache, (dict, DiskCache)):
-            image_cache = DiskCache(image_cache)
-        for css in stylesheets or []:
+        cache_folder = options['cache_folder']
+        if cache_folder is None:
+            cache_folder = {}
+        elif not isinstance(cache_folder, (dict, DiskCache)):
+            cache_folder = DiskCache(cache_folder)
+        for css in options['stylesheets'] or []:
             if not hasattr(css, 'matcher'):
                 css = CSS(
                     guess=css, media_type=html.media_type,
                     font_config=font_config, counter_style=counter_style)
             user_stylesheets.append(css)
         style_for = get_all_computed_styles(
-            html, user_stylesheets, presentational_hints, font_config,
-            counter_style, page_rules, target_collector, forms)
+            html, user_stylesheets, options['presentational_hints'],
+            font_config, counter_style, page_rules, target_collector,
+            options['pdf_forms'])
         get_image_from_uri = functools.partial(
-            original_get_image_from_uri, cache=image_cache,
-            url_fetcher=html.url_fetcher, optimize_size=optimize_size,
-            jpeg_quality=jpeg_quality, dpi=dpi)
+            original_get_image_from_uri, cache=cache_folder,
+            url_fetcher=html.url_fetcher, options=options)
         PROGRESS_LOGGER.info('Step 4 - Creating formatting structure')
         context = LayoutContext(
             style_for, get_image_from_uri, font_config, counter_style,
@@ -252,9 +251,7 @@ class Document:
         return context
 
     @classmethod
-    def _render(cls, html, stylesheets, presentational_hints, optimize_size,
-                jpeg_quality, dpi, font_config, counter_style, image_cache,
-                forms):
+    def _render(cls, html, font_config, counter_style, options):
         if font_config is None:
             font_config = FontConfiguration()
 
@@ -262,8 +259,7 @@ class Document:
             counter_style = CounterStyle()
 
         context = cls._build_layout_context(
-            html, stylesheets, presentational_hints, optimize_size,
-            jpeg_quality, dpi, font_config, counter_style, image_cache, forms)
+            html, font_config, counter_style, options)
 
         root_box = build_formatting_structure(
             html.etree_element, context.style_for, context.get_image_from_uri,
@@ -274,12 +270,11 @@ class Document:
         rendering = cls(
             [Page(page_box) for page_box in page_boxes],
             DocumentMetadata(**get_html_metadata(html)),
-            html.url_fetcher, font_config, optimize_size)
+            html.url_fetcher, font_config)
         rendering._html = html
         return rendering
 
-    def __init__(self, pages, metadata, url_fetcher, font_config,
-                 optimize_size):
+    def __init__(self, pages, metadata, url_fetcher, font_config):
         #: A list of :class:`Page` objects.
         self.pages = pages
         #: A :class:`DocumentMetadata` object.
@@ -298,9 +293,6 @@ class Document:
         # rendering is destroyed. This is needed as font_config.__del__ removes
         # fonts that may be used when rendering
         self.font_config = font_config
-        # Set of flags for PDF size optimization. Can contain "images", "fonts"
-        # and "pdf".
-        self._optimize_size = optimize_size
 
     def build_element_structure(self, structure, etree_element=None):
         if etree_element is None:
@@ -340,8 +332,7 @@ class Document:
         elif not isinstance(pages, list):
             pages = list(pages)
         return type(self)(
-            pages, self.metadata, self.url_fetcher, self.font_config,
-            self._optimize_size)
+            pages, self.metadata, self.url_fetcher, self.font_config)
 
     def make_bookmark_tree(self, scale=1, transform_pages=False):
         """Make a tree of all bookmarks in the document.
@@ -376,9 +367,7 @@ class Document:
                 page_number, matrix)
         return root
 
-    def write_pdf(self, target=None, zoom=1, attachments=None, finisher=None,
-                  identifier=None, variant=None, version=None,
-                  custom_metadata=False):
+    def write_pdf(self, target=None, zoom=1, finisher=None, **options):
         """Paint the pages in a PDF file, with metadata.
 
         :type target:
@@ -391,33 +380,31 @@ class Document:
             All CSS units are affected, including physical units like
             ``cm`` and named sizes like ``A4``.  For values other than
             1, the physical CSS units will thus be "wrong".
-        :param list attachments: A list of additional file attachments for the
-            generated PDF document or :obj:`None`. The list's elements are
-            :class:`weasyprint.Attachment` objects, filenames, URLs or
-            file-like objects.
-        :param finisher: A finisher function, that accepts the document and a
-            :class:`pydyf.PDF` object as parameters, can be passed to perform
+        :type finisher: :term:`callable`
+        :param finisher:
+            A finisher function or callable that accepts the document and a
+            :class:`pydyf.PDF` object as parameters. Can be passed to perform
             post-processing on the PDF right before the trailer is written.
-        :param bytes identifier: A bytestring used as PDF file identifier.
-        :param str variant: A PDF variant name.
-        :param str version: A PDF version number.
-        :param bool custom_metadata: A boolean defining whether custom HTML
-            metadata should be stored in the generated PDF.
+        :param options:
+            The ``options`` parameter includes by default the
+            :data:`weasyprint.DEFAULT_OPTIONS` values.
         :returns:
             The PDF as :obj:`bytes` if ``target`` is not provided or
             :obj:`None`, otherwise :obj:`None` (the PDF is written to
             ``target``).
 
         """
-        pdf = generate_pdf(
-            self, target, zoom, attachments, self._optimize_size, identifier,
-            variant, version, custom_metadata)
+        new_options = DEFAULT_OPTIONS.copy()
+        new_options.update(options)
+        options = new_options
+        pdf = generate_pdf(self, target, zoom, **options)
+
+        identifier = options['pdf_identifier']
+        compress = not options['uncompressed_pdf']
 
         if finisher:
             finisher(self, pdf)
 
-        compress = 'pdf' in self._optimize_size
-
         if target is None:
             output = io.BytesIO()
             pdf.write(output, pdf.version, identifier, compress)
diff --git a/weasyprint/html.py b/weasyprint/html.py
index c541fd56..7a4d69d2 100644
--- a/weasyprint/html.py
+++ b/weasyprint/html.py
@@ -45,9 +45,6 @@ HTML_SPACE_SEPARATED_TOKENS_RE = re.compile(f'[^{HTML_WHITESPACE}]+')
 def ascii_lower(string):
     r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
 
-    :param string: An Unicode string.
-    :returns: A new Unicode string.
-
     This is used for `ASCII case-insensitive
     <https://whatwg.org/C#ascii-case-insensitive>`_ matching.
 
@@ -66,15 +63,9 @@ def ascii_lower(string):
 
 
 def element_has_link_type(element, link_type):
-    """
-    Return whether the given element has a ``rel`` attribute with the
-    given link type.
-
-    :param link_type: Must be a lower-case string.
-
-    """
-    return any(ascii_lower(token) == link_type for token in
-               HTML_SPACE_SEPARATED_TOKENS_RE.findall(element.get('rel', '')))
+    """Return whether element has a ``rel`` attribute with given link type."""
+    tokens = HTML_SPACE_SEPARATED_TOKENS_RE.findall(element.get('rel', ''))
+    return any(ascii_lower(token) == link_type for token in tokens)
 
 
 # Maps HTML tag names to function taking an HTML element and returning a Box.
diff --git a/weasyprint/images.py b/weasyprint/images.py
index f261e25d..5a4b5216 100644
--- a/weasyprint/images.py
+++ b/weasyprint/images.py
@@ -15,6 +15,7 @@ from xml.etree import ElementTree
 import pydyf
 from PIL import Image, ImageFile, ImageOps
 
+from . import DEFAULT_OPTIONS
 from .layout.percent import percentage
 from .logger import LOGGER
 from .svg import SVG
@@ -40,8 +41,7 @@ class ImageLoadingError(ValueError):
 
 class RasterImage:
     def __init__(self, pillow_image, image_id, image_data, filename=None,
-                 cache=None, optimize_size=(), jpeg_quality=None, dpi=None,
-                 orientation='none'):
+                 cache=None, orientation='none', options=DEFAULT_OPTIONS):
         # Transpose image
         original_pillow_image = pillow_image
         pillow_image = rotate_pillow_image(pillow_image, orientation)
@@ -53,8 +53,8 @@ class RasterImage:
 
         self.id = image_id
         self._cache = {} if cache is None else cache
-        self._jpeg_quality = jpeg_quality
-        self._dpi = dpi
+        self._jpeg_quality = jpeg_quality = options['jpeg_quality']
+        self._dpi = options['dpi']
 
         if 'transparency' in pillow_image.info:
             pillow_image = pillow_image.convert('RGBA')
@@ -65,15 +65,15 @@ class RasterImage:
         self.width = pillow_image.width
         self.height = pillow_image.height
         self.ratio = (self.width / self.height) if self.height != 0 else inf
-        self.optimize = optimize = 'images' in optimize_size
+        self.optimize = optimize = options['optimize_images']
 
         if pillow_image.format in ('JPEG', 'MPO'):
             self.format = 'JPEG'
             if image_data is None or optimize or jpeg_quality is not None:
                 image_file = io.BytesIO()
                 options = {'format': 'JPEG', 'optimize': optimize}
-                if jpeg_quality is not None:
-                    options['quality'] = jpeg_quality
+                if self._jpeg_quality is not None:
+                    options['quality'] = self._jpeg_quality
                 pillow_image.save(image_file, **options)
                 image_data = image_file.getvalue()
                 filename = None
@@ -277,9 +277,8 @@ class SVGImage:
             self._url_fetcher, self._context)
 
 
-def get_image_from_uri(cache, url_fetcher, optimize_size, jpeg_quality, dpi,
-                       url, forced_mime_type=None, context=None,
-                       orientation='from-image'):
+def get_image_from_uri(cache, url_fetcher, options, url, forced_mime_type=None,
+                       context=None, orientation='from-image'):
     """Get an Image instance from an image URI."""
     if url in cache:
         return cache[url]
@@ -326,7 +325,7 @@ def get_image_from_uri(cache, url_fetcher, optimize_size, jpeg_quality, dpi,
                 image_id = md5(url.encode()).hexdigest()
                 image = RasterImage(
                     pillow_image, image_id, string, filename, cache,
-                    optimize_size, jpeg_quality, dpi, orientation)
+                    orientation, options)
 
     except (URLFetchingError, ImageLoadingError) as exception:
         LOGGER.error('Failed to load image at %r: %s', url, exception)
diff --git a/weasyprint/layout/__init__.py b/weasyprint/layout/__init__.py
index cd020205..186a5561 100644
--- a/weasyprint/layout/__init__.py
+++ b/weasyprint/layout/__init__.py
@@ -105,10 +105,12 @@ def layout_document(html, root_box, context, max_loops=8):
     This includes line breaks, page breaks, absolute size and position for all
     boxes. Page based counters might require multiple passes.
 
-    :param root_box: root of the box tree (formatting structure of the html)
-                     the pages' boxes are created from that tree, i.e. this
-                     structure is not lost during pagination
-    :returns: a list of laid out Page objects.
+    :param root_box:
+        Root of the box tree (formatting structure of the HTML). The page boxes
+        are created from that tree, this structure is not lost during
+        pagination.
+    :returns:
+        A list of laid out Page objects.
 
     """
     initialize_page_maker(context, root_box)
@@ -287,13 +289,18 @@ class LayoutContext:
         Value depends on current page.
         https://drafts.csswg.org/css-gcpm/#funcdef-string
 
-        :param store: dictionary where the resolved value is stored.
-        :param page: current page.
-        :param name: name of the named string or running element.
-        :param keyword: indicates which value of the named string or running
-                        element to use. Default is the first assignment on the
-                        current page else the most recent assignment.
-        :returns: text for string set, box for running element
+        :param dict store:
+            Dictionary where the resolved value is stored.
+        :param page:
+            Current page.
+        :param str name:
+            Name of the named string or running element.
+        :param str keyword:
+            Indicates which value of the named string or running element to
+            use. Default is the first assignment on the current page else the
+            most recent assignment.
+        :returns:
+            Text for string set, box for running element.
 
         """
         if self.current_page in store[name]:
diff --git a/weasyprint/layout/page.py b/weasyprint/layout/page.py
index 51e2e1bf..32bff16e 100644
--- a/weasyprint/layout/page.py
+++ b/weasyprint/layout/page.py
@@ -174,20 +174,21 @@ def compute_fixed_dimension(context, box, outer, vertical, top_or_left):
 
 
 def compute_variable_dimension(context, side_boxes, vertical, outer_sum):
-    """
-    Compute and set a margin box fixed dimension on ``box``, as described in:
-    https://drafts.csswg.org/css-page-3/#margin-dimension
+    """Compute and set a margin box fixed dimension on ``box``
+
+    Described in: https://drafts.csswg.org/css-page-3/#margin-dimension
 
-    :param side_boxes: Three boxes on a same side (as opposed to a corner.)
+    :param side_boxes:
+        Three boxes on a same side (as opposed to a corner).
         A list of:
         - A @*-left or @*-top margin box
         - A @*-center or @*-middle margin box
         - A @*-right or @*-bottom margin box
     :param vertical:
-        True to set height, margin-top and margin-bottom; False for width,
-        margin-left and margin-right
+        ``True`` to set height, margin-top and margin-bottom;
+        ``False`` for width, margin-left and margin-right.
     :param outer_sum:
-        The target total outer dimension (max box width or height)
+        The target total outer dimension (max box width or height).
 
     """
     box_class = VerticalBox if vertical else HorizontalBox
@@ -310,8 +311,10 @@ def make_margin_boxes(context, page, state):
 
         Return ``None`` if this margin box should not be generated.
 
-        :param at_keyword: which margin box to return, eg. '@top-left'
-        :param containing_block: as expected by :func:`resolve_percentages`.
+        :param at_keyword:
+            Which margin box to return, e.g. '@top-left'
+        :param containing_block:
+            As expected by :func:`resolve_percentages`.
 
         """
         style = context.style_for(page.page_type, at_keyword)
@@ -507,9 +510,11 @@ def make_page(context, root_box, page_type, resume_at, page_number,
     and ``resume_at`` indicates where in the document to start the next page,
     or is ``None`` if this was the last page.
 
-    :param page_number: integer, start at 1 for the first page
-    :param resume_at: as returned by ``make_page()`` for the previous page,
-                      or ``None`` for the first page.
+    :param int page_number:
+        Page number, starts at 1 for the first page.
+    :param resume_at:
+        As returned by ``make_page()`` for the previous page, or ``None`` for
+        the first page.
 
     """
     style = context.style_for(page_type)
diff --git a/weasyprint/pdf/__init__.py b/weasyprint/pdf/__init__.py
index a4ddb545..22a08b74 100644
--- a/weasyprint/pdf/__init__.py
+++ b/weasyprint/pdf/__init__.py
@@ -100,8 +100,7 @@ def _use_references(pdf, resources, images):
             alpha['SMask']['G'] = alpha['SMask']['G'].reference
 
 
-def generate_pdf(document, target, zoom, attachments, optimize_size,
-                 identifier, variant, version, custom_metadata):
+def generate_pdf(document, target, zoom, **options):
     # 0.75 = 72 PDF point per inch / 96 CSS pixel per inch
     scale = zoom * 0.75
 
@@ -109,6 +108,7 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
 
     # Set properties according to PDF variants
     mark = False
+    variant, version = options['pdf_variant'], options['pdf_version']
     if variant:
         variant_function, properties = VARIANTS[variant]
         if 'version' in properties:
@@ -116,6 +116,7 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
         if 'mark' in properties:
             mark = properties['mark']
 
+    identifier = options['pdf_identifier']
     pdf = pydyf.PDF((version or '1.7'), identifier)
     states = pydyf.Dictionary()
     x_objects = pydyf.Dictionary()
@@ -136,6 +137,7 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
 
     annot_files = {}
     pdf_pages, page_streams = [], []
+    compress = not options['uncompressed_pdf']
     for page_number, (page, links_and_anchors) in enumerate(
             zip(document.pages, page_links_and_anchors)):
         # Draw from the top-left corner
@@ -153,7 +155,6 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
         page_rectangle = (
             left / scale, top / scale,
             (right - left) / scale, (bottom - top) / scale)
-        compress = 'pdf' in optimize_size
         stream = Stream(
             document.fonts, page_rectangle, states, x_objects, patterns,
             shadings, images, mark, compress=compress)
@@ -229,7 +230,7 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
             _w3c_date_to_pdf(metadata.modified, 'modified'))
     if metadata.lang:
         pdf.catalog['Lang'] = pydyf.String(metadata.lang)
-    if custom_metadata:
+    if options['custom_metadata']:
         for key, value in metadata.custom.items():
             key = ''.join(char for char in key if char.isalnum())
             key = key.encode('ascii', errors='ignore').decode()
@@ -237,7 +238,7 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
                 pdf.info[key] = pydyf.String(value)
 
     # Embedded files
-    attachments = metadata.attachments + (attachments or [])
+    attachments = metadata.attachments + (options['attachments'] or [])
     pdf_attachments = []
     for attachment in attachments:
         pdf_attachment = write_pdf_attachment(
@@ -255,7 +256,10 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
         pdf.catalog['Names']['EmbeddedFiles'] = content.reference
 
     # Embedded fonts
-    pdf_fonts = build_fonts_dictionary(pdf, document.fonts, optimize_size)
+    subset = not options['full_fonts']
+    hinting = options['hinting']
+    pdf_fonts = build_fonts_dictionary(
+        pdf, document.fonts, compress, subset, hinting)
     pdf.add_object(pdf_fonts)
     if 'AcroForm' in pdf.catalog:
         # Include Dingbats for forms
@@ -283,7 +287,6 @@ def generate_pdf(document, target, zoom, attachments, optimize_size,
 
     # Apply PDF variants functions
     if variant:
-        compress = 'pdf' in optimize_size
         variant_function(pdf, metadata, document, page_streams, compress)
 
     return pdf
diff --git a/weasyprint/pdf/fonts.py b/weasyprint/pdf/fonts.py
index 3ddffd0a..d277a6c9 100644
--- a/weasyprint/pdf/fonts.py
+++ b/weasyprint/pdf/fonts.py
@@ -7,8 +7,7 @@ import pydyf
 from ..logger import LOGGER
 
 
-def build_fonts_dictionary(pdf, fonts, optimize_size):
-    compress = 'pdf' in optimize_size
+def build_fonts_dictionary(pdf, fonts, compress_pdf, subset, hinting):
     pdf_fonts = pydyf.Dictionary()
     fonts_by_file_hash = {}
     for font in fonts.values():
@@ -22,10 +21,9 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
 
         # Clean font, optimize and handle emojis
         cmap = {}
-        if 'fonts' in optimize_size and not font.used_in_forms:
+        if subset and not font.used_in_forms:
             for file_font in file_fonts:
                 cmap = {**cmap, **file_font.cmap}
-        hinting = 'hinting' not in optimize_size
         font.clean(cmap, hinting)
 
         # Include font
@@ -34,15 +32,12 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
         else:
             font_extra = pydyf.Dictionary({'Length1': len(font.file_content)})
         font_stream = pydyf.Stream(
-            [font.file_content], font_extra, compress=compress)
+            [font.file_content], font_extra, compress=compress_pdf)
         pdf.add_object(font_stream)
         font_references_by_file_hash[file_hash] = font_stream.reference
 
     for font in fonts.values():
-        optimize = (
-            'fonts' in optimize_size and
-            font.ttfont and not font.used_in_forms)
-        if optimize:
+        if subset and font.ttfont and not font.used_in_forms:
             # Only store widths and map for used glyphs
             font_widths = font.widths
             cmap = font.cmap
@@ -82,7 +77,7 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
             b'1 begincodespacerange',
             b'<0000> <ffff>',
             b'endcodespacerange',
-            f'{len(cmap)} beginbfchar'.encode()], compress=compress)
+            f'{len(cmap)} beginbfchar'.encode()], compress=compress_pdf)
         for glyph, text in cmap.items():
             unicode_codepoints = ''.join(
                 f'{letter.encode("utf-16-be").hex()}' for letter in text)
@@ -104,7 +99,7 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
 
         if font.bitmap:
             _build_bitmap_font_dictionary(
-                font_dictionary, pdf, font, widths, optimize_size)
+                font_dictionary, pdf, font, widths, compress_pdf, subset)
         else:
             font_descriptor = pydyf.Dictionary({
                 'Type': '/FontDescriptor',
@@ -128,7 +123,7 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
                     bits[cid] = '1'
                 stream = pydyf.Stream(
                     (int(''.join(bits), 2).to_bytes(padded_width, 'big'),),
-                    compress=compress)
+                    compress=compress_pdf)
                 pdf.add_object(stream)
                 font_descriptor['CIDSet'] = stream.reference
             if font.type == 'otf':
@@ -158,12 +153,11 @@ def build_fonts_dictionary(pdf, fonts, optimize_size):
 
 
 def _build_bitmap_font_dictionary(font_dictionary, pdf, font, widths,
-                                  optimize_size):
-    compress = 'pdf' in optimize_size
+                                  compress_pdf, subset):
     # https://docs.microsoft.com/typography/opentype/spec/ebdt
     font_dictionary['FontBBox'] = pydyf.Array([0, 0, 1, 1])
     font_dictionary['FontMatrix'] = pydyf.Array([1, 0, 0, 1, 0, 0])
-    if 'fonts' in optimize_size:
+    if subset:
         chars = tuple(sorted(font.cmap))
     else:
         chars = tuple(range(256))
@@ -312,7 +306,7 @@ def _build_bitmap_font_dictionary(font_dictionary, pdf, font, widths,
             b'/BPC 1',
             b'/D [1 0]',
             b'ID', bitmap, b'EI'
-        ], compress=compress)
+        ], compress=compress_pdf)
         pdf.add_object(bitmap_stream)
         char_procs[glyph_id] = bitmap_stream.reference
 
diff --git a/weasyprint/text/line_break.py b/weasyprint/text/line_break.py
index 6328b946..3cf23e41 100644
--- a/weasyprint/text/line_break.py
+++ b/weasyprint/text/line_break.py
@@ -235,15 +235,7 @@ class Layout:
 
 
 def create_layout(text, style, context, max_width, justification_spacing):
-    """Return an opaque Pango layout with default Pango line-breaks.
-
-    :param text: Unicode
-    :param style: a style dict of computed values
-    :param max_width:
-        The maximum available width in the same unit as ``style['font_size']``,
-        or ``None`` for unlimited width.
-
-    """
+    """Return an opaque Pango layout with default Pango line-breaks."""
     layout = Layout(context, style, justification_spacing, max_width)
 
     # Make sure that max_width * Pango.SCALE == max_width * 1024 fits in a
diff --git a/weasyprint/urls.py b/weasyprint/urls.py
index abfa53c1..a2c6baaa 100644
--- a/weasyprint/urls.py
+++ b/weasyprint/urls.py
@@ -175,9 +175,12 @@ def default_url_fetcher(url, timeout=10, ssl_context=None):
     ``url_fetcher`` argument to :class:`HTML` or :class:`CSS`.
     (See :ref:`URL Fetchers`.)
 
-    :param str url: The URL of the resource to fetch.
-    :param int timeout: The number of seconds before HTTP requests are dropped.
-    :param ssl.SSLContext ssl_context: An SSL context used for HTTP requests.
+    :param str url:
+        The URL of the resource to fetch.
+    :param int timeout:
+        The number of seconds before HTTP requests are dropped.
+    :param ssl.SSLContext ssl_context:
+        An SSL context used for HTTP requests.
     :raises: An exception indicating failure, e.g. :obj:`ValueError` on
         syntactically invalid URL.
     :returns: A :obj:`dict` with the following keys:


Test patch:
diff --git a/tests/conftest.py b/tests/conftest.py
index 4daf4745..b8f3b6ed 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -73,15 +73,10 @@ def document_write_png(self, target=None, resolution=96, antialiasing=1,
             shutil.copyfileobj(png, fd)
 
 
-def html_write_png(self, target=None, stylesheets=None, resolution=96,
-                   presentational_hints=False,
-                   optimize_size=('fonts', 'hinting', 'pdf'), font_config=None,
-                   counter_style=None, image_cache=None):
-    return self.render(
-        stylesheets, presentational_hints=presentational_hints,
-        optimize_size=optimize_size, font_config=font_config,
-        counter_style=counter_style, image_cache=image_cache).write_png(
-            target, resolution)
+def html_write_png(self, target=None, font_config=None, counter_style=None,
+                   resolution=96, **options):
+    document = self.render(font_config, counter_style, **options)
+    return document.write_png(target, resolution)
 
 
 Document.write_png = document_write_png
diff --git a/tests/test_api.py b/tests/test_api.py
index 6049af31..e0dacd83 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -6,6 +6,7 @@ import os
 import sys
 import unicodedata
 import zlib
+from functools import partial
 from pathlib import Path
 from urllib.parse import urljoin, uses_relative
 
@@ -75,14 +76,11 @@ def _check_doc1(html, has_base_url=True):
         assert html.base_url is None
 
 
-def _run(args, stdin=b''):
+def _run(args, stdin=b'', uncompressed=False):
     stdin = io.BytesIO(stdin)
     stdout = io.BytesIO()
-    try:
-        __main__.HTML = FakeHTML
-        __main__.main(args.split(), stdin=stdin, stdout=stdout)
-    finally:
-        __main__.HTML = HTML
+    HTML = partial(FakeHTML, force_uncompressed_pdf=uncompressed)
+    __main__.main(args.split(), stdin=stdin, stdout=stdout, HTML=HTML)
     return stdout.getvalue()
 
 
@@ -303,12 +301,12 @@ def test_command_line_render(tmpdir):
         tmpdir.join(name).write_binary(pattern_bytes)
 
     # Reference
-    optimize_size = ('fonts', 'hinting', 'pdf')
-    html_obj = FakeHTML(string=combined, base_url='dummy.html')
-    pdf_bytes = html_obj.write_pdf(optimize_size=optimize_size)
+    html_obj = FakeHTML(
+        string=combined, base_url='dummy.html', force_uncompressed_pdf=False)
+    pdf_bytes = html_obj.write_pdf()
     rotated_pdf_bytes = FakeHTML(
         string=combined, base_url='dummy.html',
-        media_type='screen').write_pdf(optimize_size=optimize_size)
+        media_type='screen', force_uncompressed_pdf=False).write_pdf()
 
     tmpdir.join('no_css.html').write_binary(html)
     tmpdir.join('combined.html').write_binary(combined)
@@ -361,42 +359,34 @@ def test_command_line_render(tmpdir):
 
     os.environ['SOURCE_DATE_EPOCH'] = '0'
     _run('not_optimized.html out15.pdf')
-    _run('not_optimized.html out16.pdf -O images')
-    _run('not_optimized.html out17.pdf -O fonts')
-    _run('not_optimized.html out18.pdf -O fonts -O images')
-    _run('not_optimized.html out19.pdf -O all')
-    _run('not_optimized.html out20.pdf -O none')
-    _run('not_optimized.html out21.pdf -O none -O all')
-    _run('not_optimized.html out22.pdf -O all -O none')
-    _run('not_optimized.html out23.pdf -O pdf')
-    _run('not_optimized.html out24.pdf -O none -O fonts -O pdf -O hinting')
-    _run('not_optimized.html out25.pdf -O all -j 10')
-    _run('not_optimized.html out26.pdf -O all -j 10 -D 1')
-    _run(f'not_optimized.html out27.pdf -c {tmpdir}')
+    _run('not_optimized.html out16.pdf --optimize-images')
+    _run('not_optimized.html out17.pdf --optimize-images -j 10')
+    _run('not_optimized.html out18.pdf --optimize-images -j 10 -D 1')
+    _run('not_optimized.html out19.pdf --hinting')
+    _run('not_optimized.html out20.pdf --full-fonts')
+    _run('not_optimized.html out21.pdf --full-fonts --uncompressed-pdf')
+    _run(f'not_optimized.html out22.pdf -c {tmpdir}')
     assert (
-        len(tmpdir.join('out26.pdf').read_binary()) <
-        len(tmpdir.join('out25.pdf').read_binary()) <
+        len(tmpdir.join('out18.pdf').read_binary()) <
+        len(tmpdir.join('out17.pdf').read_binary()) <
         len(tmpdir.join('out16.pdf').read_binary()) <
         len(tmpdir.join('out15.pdf').read_binary()) <
-        len(tmpdir.join('out20.pdf').read_binary()))
+        len(tmpdir.join('out19.pdf').read_binary()) <
+        len(tmpdir.join('out20.pdf').read_binary()) <
+        len(tmpdir.join('out21.pdf').read_binary()))
     assert len({
         tmpdir.join(f'out{i}.pdf').read_binary()
-        for i in (16, 18, 19, 21)}) == 1
-    assert len({
-        tmpdir.join(f'out{i}.pdf').read_binary()
-        for i in (15, 17, 23, 24, 27)}) == 1
-    assert len({
-        tmpdir.join(f'out{i}.pdf').read_binary()
-        for i in (20, 22)}) == 1
+        for i in (15, 22)}) == 1
     os.environ.pop('SOURCE_DATE_EPOCH')
 
-    stdout = _run('-O none combined.html -')
+    stdout = _run('combined.html -', uncompressed=True)
     assert stdout.count(b'attachment') == 0
-    stdout = _run('-O none combined.html -')
+    stdout = _run('combined.html -', uncompressed=True)
     assert stdout.count(b'attachment') == 0
-    stdout = _run('-O none -a pattern.png combined.html -')
+    stdout = _run('-a pattern.png combined.html -', uncompressed=True)
     assert stdout.count(b'attachment') == 1
-    stdout = _run('-O none -a style.css -a pattern.png combined.html -')
+    stdout = _run(
+        '-a style.css -a pattern.png combined.html -', uncompressed=True)
     assert stdout.count(b'attachment') == 2
 
     os.mkdir('subdirectory')
@@ -431,7 +421,8 @@ def test_command_line_render(tmpdir):
     (4, '2.0'),
 ))
 def test_pdfa(version, pdf_version):
-    stdout = _run(f'--pdf-variant=pdf/a-{version}b -O none - -', b'test')
+    stdout = _run(
+        f'--pdf-variant=pdf/a-{version}b - -', b'test', uncompressed=True)
     assert f'PDF-{pdf_version}'.encode() in stdout
     assert f'part="{version}"'.encode() in stdout
 
@@ -447,7 +438,7 @@ def test_pdfa_compressed(version, pdf_version):
 
 
 def test_pdfua():
-    stdout = _run('--pdf-variant=pdf/ua-1 -O none - -', b'test')
+    stdout = _run('--pdf-variant=pdf/ua-1 - -', b'test', uncompressed=True)
     assert b'part="1"' in stdout
 
 
@@ -456,34 +447,35 @@ def test_pdfua_compressed():
 
 
 def test_pdf_identifier():
-    stdout = _run('--pdf-identifier=abc -O none - -', b'test')
+    stdout = _run('--pdf-identifier=abc - -', b'test', uncompressed=True)
     assert b'abc' in stdout
 
 
 def test_pdf_version():
-    stdout = _run('--pdf-version=1.4 -O none - -', b'test')
+    stdout = _run('--pdf-version=1.4 - -', b'test', uncompressed=True)
     assert b'PDF-1.4' in stdout
 
 
 def test_pdf_custom_metadata():
     stdout = _run(
-        '--custom-metadata -O none - -',
-        b'<meta name=key content=value />')
+        '--custom-metadata - -', b'<meta name=key content=value />',
+        uncompressed=True)
     assert b'/key' in stdout
     assert b'value' in stdout
 
 
 def test_bad_pdf_custom_metadata():
     stdout = _run(
-        '--custom-metadata -O none - -',
-        '<meta name=é content=value />'.encode('latin1'))
+        '--custom-metadata - -',
+        '<meta name=é content=value />'.encode('latin1'), uncompressed=True)
     assert b'value' not in stdout
 
 
 def test_partial_pdf_custom_metadata():
     stdout = _run(
-        '--custom-metadata -O none - -',
-        '<meta name=a.b/céd0 content=value />'.encode('latin1'))
+        '--custom-metadata - -',
+        '<meta name=a.b/céd0 content=value />'.encode('latin1'),
+        uncompressed=True)
     assert b'/abcd0' in stdout
     assert b'value' in stdout
 
@@ -494,10 +486,10 @@ def test_partial_pdf_custom_metadata():
     (b'<textarea></textarea>', b'/Tx'),
 ))
 def test_pdf_inputs(html, field):
-    stdout = _run('--pdf-forms -O none - -', html)
+    stdout = _run('--pdf-forms - -', html, uncompressed=True)
     assert b'AcroForm' in stdout
     assert field in stdout
-    stdout = _run('- -', html)
+    stdout = _run('- -', html, uncompressed=True)
     assert b'AcroForm' not in stdout
 
 
@@ -508,8 +500,10 @@ def test_pdf_inputs(html, field):
 ))
 def test_appearance(css, with_forms, without_forms):
     html = f'<input style="{css}">'.encode()
-    assert (b'AcroForm' in _run('--pdf-forms -O none - -', html)) is with_forms
-    assert (b'AcroForm' in _run(' -O none - -', html)) is without_forms
+    assert with_forms is (
+        b'AcroForm' in _run('--pdf-forms - -', html, uncompressed=True))
+    assert without_forms is (
+        b'AcroForm' in _run(' - -', html, uncompressed=True))
 
 
 def test_reproducible():
@@ -565,20 +559,20 @@ def test_low_level_api(assert_pixels_equal):
     assert pdf_bytes.startswith(b'%PDF')
 
     png_bytes = html.write_png(stylesheets=[css])
-    document = html.render([css])
+    document = html.render(stylesheets=[css])
     page, = document.pages
     assert page.width == 8
     assert page.height == 8
     assert document.write_png() == png_bytes
     assert document.copy([page]).write_png() == png_bytes
 
-    document = html.render([css])
+    document = html.render(stylesheets=[css])
     page, = document.pages
     assert (page.width, page.height) == (8, 8)
     png_bytes = document.write_png(resolution=192)
     check_png_pattern(assert_pixels_equal, png_bytes, x2=True)
 
-    document = html.render([css])
+    document = html.render(stylesheets=[css])
     page, = document.pages
     assert (page.width, page.height) == (8, 8)
     # A resolution that is not multiple of 96:
diff --git a/tests/test_pdf.py b/tests/test_pdf.py
index 3d4dcdd0..9c37f61e 100644
--- a/tests/test_pdf.py
+++ b/tests/test_pdf.py
@@ -537,8 +537,7 @@ def test_embed_images_from_pages():
         string='<img src="not-optimized.jpg">').render().pages
     document = Document(
         (page1, page2), metadata=DocumentMetadata(),
-        font_config=FontConfiguration(), url_fetcher=None,
-        optimize_size=()).write_pdf()
+        font_config=FontConfiguration(), url_fetcher=None).write_pdf()
     assert document.count(b'/Filter /DCTDecode') == 2
 
 
diff --git a/tests/testing_utils.py b/tests/testing_utils.py
index ba618cb9..d0577f3f 100644
--- a/tests/testing_utils.py
+++ b/tests/testing_utils.py
@@ -8,7 +8,7 @@ import sys
 import threading
 import wsgiref.simple_server
 
-from weasyprint import CSS, HTML, images
+from weasyprint import CSS, DEFAULT_OPTIONS, HTML, images
 from weasyprint.css import get_all_computed_styles
 from weasyprint.css.counters import CounterStyle
 from weasyprint.css.targets import TargetCollector
@@ -48,23 +48,20 @@ PROPER_CHILDREN = dict((key, tuple(map(tuple, value))) for key, value in {
 
 class FakeHTML(HTML):
     """Like weasyprint.HTML, but with a lighter UA stylesheet."""
+    def __init__(self, *args, force_uncompressed_pdf=True, **kwargs):
+        super().__init__(*args, **kwargs)
+        self._force_uncompressed_pdf = force_uncompressed_pdf
+
     def _ua_stylesheets(self, forms=False):
         return [
             TEST_UA_STYLESHEET if stylesheet == HTML5_UA_STYLESHEET
             else stylesheet for stylesheet in super()._ua_stylesheets(forms)]
 
-    def write_pdf(self, target=None, stylesheets=None, zoom=1,
-                  attachments=None, finisher=None, presentational_hints=False,
-                  optimize_size=('fonts',), jpeg_quality=None, dpi=None,
-                  font_config=None, counter_style=None, image_cache=None,
-                  identifier=None, variant=None, version=None, forms=False,
-                  custom_metadata=False):
-        # Override function to set PDF size optimization to False by default
-        return super().write_pdf(
-            target, stylesheets, zoom, attachments, finisher,
-            presentational_hints, optimize_size, jpeg_quality, dpi,
-            font_config, counter_style, image_cache, identifier, variant,
-            version, forms, custom_metadata)
+    def write_pdf(self, target=None, zoom=1, finisher=None, **options):
+        # Override function to force the generation of uncompressed PDFs
+        if self._force_uncompressed_pdf:
+            options['uncompressed_pdf'] = True
+        return super().write_pdf(target, zoom, finisher, **options)
 
 
 def resource_filename(basename):
@@ -195,7 +192,7 @@ def _parse_base(html_content, base_url=BASE_URL):
     style_for = get_all_computed_styles(document, counter_style=counter_style)
     get_image_from_uri = functools.partial(
         images.get_image_from_uri, cache={}, url_fetcher=document.url_fetcher,
-        optimize_size=(), jpeg_quality=None, dpi=None)
+        options=DEFAULT_OPTIONS)
     target_collector = TargetCollector()
     footnotes = []
     return (