2022-02-14 09:11:30 +03:00
|
|
|
"""The Awesome Document Factory.
|
2011-08-09 14:45:51 +04:00
|
|
|
|
2022-02-14 09:11:30 +03:00
|
|
|
The public API is what is accessible from this "root" packages without
|
|
|
|
importing sub-modules.
|
2011-08-19 13:22:31 +04:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
2019-03-01 13:38:03 +03:00
|
|
|
import contextlib
|
2024-02-02 18:42:10 +03:00
|
|
|
from datetime import datetime
|
|
|
|
from os.path import getctime, getmtime
|
2018-08-21 17:17:00 +03:00
|
|
|
from pathlib import Path
|
2022-05-05 16:34:56 +03:00
|
|
|
from urllib.parse import urljoin
|
2018-01-28 02:02:13 +03:00
|
|
|
|
2017-06-30 18:54:02 +03:00
|
|
|
import cssselect2
|
2019-03-01 13:38:03 +03:00
|
|
|
import html5lib
|
2017-03-26 12:42:50 +03:00
|
|
|
import tinycss2
|
2016-01-15 14:47:03 +03:00
|
|
|
|
2024-06-21 18:46:31 +03:00
|
|
|
VERSION = __version__ = '62.3'
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2023-04-13 20:34:22 +03:00
|
|
|
#: 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.
|
2024-07-09 12:54:38 +03:00
|
|
|
#: :param bool srgb:
|
|
|
|
#: Whether sRGB color profile should be included and set as default for
|
|
|
|
#: device-dependant RGB colors.
|
2023-04-13 20:34:22 +03:00
|
|
|
#: :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.
|
2023-04-14 16:28:36 +03:00
|
|
|
#: :type cache: :obj:`dict`, :class:`pathlib.Path` or :obj:`str`
|
|
|
|
#: :param cache:
|
|
|
|
#: A dictionary used to cache images in memory, or a folder path where
|
|
|
|
#: images are temporarily stored.
|
2023-04-13 20:34:22 +03:00
|
|
|
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,
|
2024-07-09 12:54:38 +03:00
|
|
|
'srgb': False,
|
2023-04-13 20:34:22 +03:00
|
|
|
'optimize_images': False,
|
|
|
|
'jpeg_quality': None,
|
|
|
|
'dpi': None,
|
|
|
|
'full_fonts': False,
|
|
|
|
'hinting': False,
|
2023-04-14 16:28:36 +03:00
|
|
|
'cache': None,
|
2023-04-13 20:34:22 +03:00
|
|
|
}
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2021-02-18 13:39:44 +03:00
|
|
|
__all__ = [
|
2023-04-13 20:34:22 +03:00
|
|
|
'HTML', 'CSS', 'DEFAULT_OPTIONS', 'Attachment', 'Document', 'Page',
|
|
|
|
'default_url_fetcher', 'VERSION', '__version__']
|
2012-05-15 15:40:36 +04:00
|
|
|
|
2012-07-13 14:24:55 +04:00
|
|
|
|
2016-01-15 14:47:03 +03:00
|
|
|
# Import after setting the version, as the version is used in other modules
|
2024-03-17 13:34:03 +03:00
|
|
|
from .urls import ( # noqa: I001, E402
|
2019-03-01 13:38:03 +03:00
|
|
|
fetch, default_url_fetcher, path2url, ensure_url, url_is_absolute)
|
2024-03-17 13:34:03 +03:00
|
|
|
from .logger import LOGGER, PROGRESS_LOGGER # noqa: E402
|
2016-01-15 14:47:03 +03:00
|
|
|
# Some imports are at the end of the file (after the CSS class)
|
2013-02-25 18:21:25 +04:00
|
|
|
# to work around circular imports.
|
2012-07-13 14:24:55 +04:00
|
|
|
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2022-05-05 16:34:56 +03:00
|
|
|
def _find_base_url(html_document, fallback_base_url):
|
|
|
|
"""Return the base URL for the document.
|
|
|
|
|
2022-06-28 16:57:49 +03:00
|
|
|
See https://www.w3.org/TR/html5/urls.html#document-base-url
|
2022-05-05 16:34:56 +03:00
|
|
|
|
|
|
|
"""
|
|
|
|
first_base_element = next(iter(html_document.iter('base')), None)
|
|
|
|
if first_base_element is not None:
|
|
|
|
href = first_base_element.get('href', '').strip()
|
|
|
|
if href:
|
|
|
|
return urljoin(fallback_base_url, href)
|
|
|
|
return fallback_base_url
|
|
|
|
|
|
|
|
|
2020-01-02 14:06:58 +03:00
|
|
|
class HTML:
|
2020-05-30 02:27:13 +03:00
|
|
|
"""HTML document parsed by html5lib.
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2012-09-19 19:37:52 +04:00
|
|
|
You can just create an instance with a positional argument:
|
|
|
|
``doc = HTML(something)``
|
|
|
|
The class will try to guess if the input is a filename, an absolute URL,
|
2019-02-22 13:34:46 +03:00
|
|
|
or a :term:`file object`.
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2012-09-19 19:37:52 +04:00
|
|
|
Alternatively, use **one** named argument so that no guessing is involved:
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2019-02-22 13:34:46 +03:00
|
|
|
:type filename: str or pathlib.Path
|
2023-04-13 20:34:22 +03:00
|
|
|
:param filename:
|
|
|
|
A filename, relative to the current directory, or absolute.
|
|
|
|
:param str url:
|
|
|
|
An absolute, fully qualified URL.
|
2019-02-22 13:34:46 +03:00
|
|
|
:type file_obj: :term:`file object`
|
2023-04-13 20:34:22 +03:00
|
|
|
:param file_obj:
|
|
|
|
Any object with a ``read`` method.
|
|
|
|
:param str string:
|
|
|
|
A string of HTML source.
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2017-04-28 21:36:14 +03:00
|
|
|
Specifying multiple inputs is an error:
|
|
|
|
``HTML(filename="foo.html", url="localhost://bar.html")``
|
2019-02-22 13:34:46 +03:00
|
|
|
will raise a :obj:`TypeError`.
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2012-09-19 19:37:52 +04:00
|
|
|
You can also pass optional named arguments:
|
2012-02-27 18:07:41 +04:00
|
|
|
|
2023-04-13 20:34:22 +03:00
|
|
|
:param str encoding:
|
|
|
|
Force the source character encoding.
|
2024-01-04 12:46:51 +03:00
|
|
|
:type base_url: str or pathlib.Path
|
|
|
|
:param base_url:
|
2023-04-13 20:34:22 +03:00
|
|
|
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.
|
2012-02-27 18:07:41 +04:00
|
|
|
|
|
|
|
"""
|
|
|
|
def __init__(self, guess=None, filename=None, url=None, file_obj=None,
|
2017-06-30 21:12:53 +03:00
|
|
|
string=None, encoding=None, base_url=None,
|
2014-04-22 22:40:46 +04:00
|
|
|
url_fetcher=default_url_fetcher, media_type='print'):
|
2019-01-04 01:02:44 +03:00
|
|
|
PROGRESS_LOGGER.info(
|
2017-07-25 14:58:18 +03:00
|
|
|
'Step 1 - Fetching and parsing HTML - %s',
|
|
|
|
guess or filename or url or
|
|
|
|
getattr(file_obj, 'name', 'HTML string'))
|
2024-01-04 12:46:51 +03:00
|
|
|
if isinstance(base_url, Path):
|
|
|
|
base_url = str(base_url)
|
2013-06-20 15:58:24 +04:00
|
|
|
result = _select_source(
|
2017-06-30 21:12:53 +03:00
|
|
|
guess, filename, url, file_obj, string, base_url, url_fetcher)
|
2013-06-20 15:58:24 +04:00
|
|
|
with result as (source_type, source, base_url, protocol_encoding):
|
2018-01-14 03:48:17 +03:00
|
|
|
if isinstance(source, str):
|
2017-07-03 16:19:05 +03:00
|
|
|
result = html5lib.parse(source, namespaceHTMLElements=False)
|
2012-05-24 18:47:40 +04:00
|
|
|
else:
|
2023-12-17 00:21:15 +03:00
|
|
|
kwargs = {'namespaceHTMLElements': False}
|
|
|
|
if protocol_encoding is not None:
|
|
|
|
kwargs['transport_encoding'] = protocol_encoding
|
|
|
|
if encoding is not None:
|
|
|
|
kwargs['override_encoding'] = encoding
|
|
|
|
result = html5lib.parse(source, **kwargs)
|
2022-05-05 16:34:56 +03:00
|
|
|
self.base_url = _find_base_url(result, base_url)
|
2012-07-13 14:24:55 +04:00
|
|
|
self.url_fetcher = url_fetcher
|
2012-08-02 15:04:31 +04:00
|
|
|
self.media_type = media_type
|
2017-07-03 16:19:05 +03:00
|
|
|
self.wrapper_element = cssselect2.ElementWrapper.from_html_root(
|
2017-07-07 12:14:07 +03:00
|
|
|
result, content_language=None)
|
2017-07-03 16:19:05 +03:00
|
|
|
self.etree_element = self.wrapper_element.etree_element
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2023-01-23 14:38:12 +03:00
|
|
|
def _ua_stylesheets(self, forms=False):
|
|
|
|
if forms:
|
|
|
|
return [HTML5_UA_STYLESHEET, HTML5_UA_FORM_STYLESHEET]
|
2012-02-16 21:52:36 +04:00
|
|
|
return [HTML5_UA_STYLESHEET]
|
|
|
|
|
2019-12-24 16:39:40 +03:00
|
|
|
def _ua_counter_style(self):
|
|
|
|
return [HTML5_UA_COUNTER_STYLE.copy()]
|
|
|
|
|
2016-08-31 23:33:26 +03:00
|
|
|
def _ph_stylesheets(self):
|
|
|
|
return [HTML5_PH_STYLESHEET]
|
|
|
|
|
2023-04-13 20:34:22 +03:00
|
|
|
def render(self, font_config=None, counter_style=None, **options):
|
2021-04-02 17:23:28 +03:00
|
|
|
"""Lay out and paginate the document, but do not (yet) export it.
|
2012-09-12 21:33:16 +04:00
|
|
|
|
2021-02-18 23:03:40 +03:00
|
|
|
This returns a :class:`document.Document` object which provides
|
2012-10-08 21:51:18 +04:00
|
|
|
access to individual pages and various meta-data.
|
|
|
|
See :meth:`write_pdf` to get a PDF directly.
|
|
|
|
|
2021-02-18 23:03:40 +03:00
|
|
|
:type font_config: :class:`text.fonts.FontConfiguration`
|
2023-04-13 20:34:22 +03:00
|
|
|
:param font_config:
|
|
|
|
A font configuration handling ``@font-face`` rules.
|
2021-02-18 23:03:40 +03:00
|
|
|
:type counter_style: :class:`css.counters.CounterStyle`
|
2023-04-13 20:34:22 +03:00
|
|
|
:param counter_style:
|
|
|
|
A dictionary storing ``@counter-style`` rules.
|
|
|
|
:param options:
|
|
|
|
The ``options`` parameter includes by default the
|
|
|
|
:data:`DEFAULT_OPTIONS` values.
|
2021-02-18 23:03:40 +03:00
|
|
|
:returns: A :class:`document.Document` object.
|
2012-09-20 19:21:44 +04:00
|
|
|
|
2012-09-12 21:33:16 +04:00
|
|
|
"""
|
2024-07-03 11:18:46 +03:00
|
|
|
for unknown in set(options) - set(DEFAULT_OPTIONS):
|
|
|
|
LOGGER.warning('Unknown rendering option: %s.', unknown)
|
2023-04-13 20:34:22 +03:00
|
|
|
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):
|
2012-10-08 21:51:18 +04:00
|
|
|
"""Render the document to a PDF file.
|
|
|
|
|
|
|
|
This is a shortcut for calling :meth:`render`, then
|
|
|
|
:meth:`Document.write_pdf() <document.Document.write_pdf>`.
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2021-02-18 23:03:40 +03:00
|
|
|
:type target:
|
|
|
|
:class:`str`, :class:`pathlib.Path` or :term:`file object`
|
2012-02-15 21:49:37 +04:00
|
|
|
:param target:
|
2019-02-22 13:34:46 +03:00
|
|
|
A filename where the PDF file is generated, a file object, or
|
|
|
|
:obj:`None`.
|
2021-02-18 23:03:40 +03:00
|
|
|
:param float zoom:
|
2017-04-28 21:36:14 +03:00
|
|
|
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
|
2018-01-28 02:02:13 +03:00
|
|
|
1, the physical CSS units will thus be "wrong".
|
2023-04-13 20:34:22 +03:00
|
|
|
: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
|
2021-08-23 10:47:49 +03:00
|
|
|
post-processing on the PDF right before the trailer is written.
|
2021-02-18 23:03:40 +03:00
|
|
|
:type font_config: :class:`text.fonts.FontConfiguration`
|
2023-04-13 20:34:22 +03:00
|
|
|
:param font_config:
|
|
|
|
A font configuration handling ``@font-face`` rules.
|
2021-02-18 23:03:40 +03:00
|
|
|
:type counter_style: :class:`css.counters.CounterStyle`
|
2023-04-13 20:34:22 +03:00
|
|
|
:param counter_style:
|
|
|
|
A dictionary storing ``@counter-style`` rules.
|
|
|
|
:param options:
|
|
|
|
The ``options`` parameter includes by default the
|
|
|
|
:data:`DEFAULT_OPTIONS` values.
|
2012-02-15 21:49:37 +04:00
|
|
|
:returns:
|
2019-02-22 13:34:46 +03:00
|
|
|
The PDF as :obj:`bytes` if ``target`` is not provided or
|
2012-10-08 21:51:18 +04:00
|
|
|
:obj:`None`, otherwise :obj:`None` (the PDF is written to
|
2019-02-22 13:34:46 +03:00
|
|
|
``target``).
|
2012-09-19 19:37:52 +04:00
|
|
|
|
2012-02-15 21:49:37 +04:00
|
|
|
"""
|
2023-04-13 20:34:22 +03:00
|
|
|
new_options = DEFAULT_OPTIONS.copy()
|
|
|
|
new_options.update(options)
|
|
|
|
options = new_options
|
2020-06-22 17:32:12 +03:00
|
|
|
return (
|
2023-04-13 20:34:22 +03:00
|
|
|
self.render(font_config, counter_style, **options)
|
|
|
|
.write_pdf(target, zoom, finisher, **options))
|
2012-02-15 21:49:37 +04:00
|
|
|
|
|
|
|
|
2020-01-02 14:06:58 +03:00
|
|
|
class CSS:
|
2020-05-30 02:27:13 +03:00
|
|
|
"""CSS stylesheet parsed by tinycss2.
|
2012-09-19 19:37:52 +04:00
|
|
|
|
2019-01-23 02:12:01 +03:00
|
|
|
An instance is created in the same way as :class:`HTML`, with the same
|
|
|
|
arguments.
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2017-05-03 10:22:19 +03:00
|
|
|
An additional argument called ``font_config`` must be provided to handle
|
2021-12-11 20:39:58 +03:00
|
|
|
``@font-face`` rules. The same ``text.fonts.FontConfiguration`` object
|
2021-02-08 02:53:27 +03:00
|
|
|
must be used for different ``CSS`` objects applied to the same document.
|
2017-05-03 10:22:19 +03:00
|
|
|
|
2019-02-21 19:34:56 +03:00
|
|
|
``CSS`` objects have no public attributes or methods. They are only meant
|
2021-02-18 23:03:40 +03:00
|
|
|
to be used in the :meth:`HTML.write_pdf` and :meth:`HTML.render` methods
|
2020-10-26 19:26:01 +03:00
|
|
|
of :class:`HTML` objects.
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2012-02-27 18:07:41 +04:00
|
|
|
"""
|
|
|
|
def __init__(self, guess=None, filename=None, url=None, file_obj=None,
|
2012-03-24 16:39:31 +04:00
|
|
|
string=None, encoding=None, base_url=None,
|
2012-08-02 15:04:31 +04:00
|
|
|
url_fetcher=default_url_fetcher, _check_mime_type=False,
|
2019-12-24 16:39:40 +03:00
|
|
|
media_type='print', font_config=None, counter_style=None,
|
|
|
|
matcher=None, page_rules=None):
|
2019-01-04 01:02:44 +03:00
|
|
|
PROGRESS_LOGGER.info(
|
2017-07-25 14:58:18 +03:00
|
|
|
'Step 2 - Fetching and parsing CSS - %s',
|
|
|
|
filename or url or getattr(file_obj, 'name', 'CSS string'))
|
2013-06-20 15:58:24 +04:00
|
|
|
result = _select_source(
|
2017-06-30 21:12:53 +03:00
|
|
|
guess, filename, url, file_obj, string,
|
2012-07-13 14:24:55 +04:00
|
|
|
base_url=base_url, url_fetcher=url_fetcher,
|
2016-10-28 18:44:09 +03:00
|
|
|
check_css_mime_type=_check_mime_type)
|
2013-06-20 15:58:24 +04:00
|
|
|
with result as (source_type, source, base_url, protocol_encoding):
|
2023-12-17 01:07:55 +03:00
|
|
|
if source_type == 'file_obj':
|
|
|
|
source = source.read()
|
|
|
|
if isinstance(source, str):
|
2012-03-24 16:39:31 +04:00
|
|
|
# unicode, no encoding
|
2017-03-26 12:42:50 +03:00
|
|
|
stylesheet = tinycss2.parse_stylesheet(source)
|
2013-06-20 15:58:24 +04:00
|
|
|
else:
|
2017-03-26 12:42:50 +03:00
|
|
|
stylesheet, encoding = tinycss2.parse_stylesheet_bytes(
|
|
|
|
source, environment_encoding=encoding,
|
2013-06-20 15:58:24 +04:00
|
|
|
protocol_encoding=protocol_encoding)
|
2012-03-24 16:39:31 +04:00
|
|
|
self.base_url = base_url
|
2017-06-30 18:54:02 +03:00
|
|
|
self.matcher = matcher or cssselect2.Matcher()
|
2017-10-06 17:20:23 +03:00
|
|
|
self.page_rules = [] if page_rules is None else page_rules
|
2016-09-24 16:36:26 +03:00
|
|
|
preprocess_stylesheet(
|
2017-06-30 18:54:02 +03:00
|
|
|
media_type, base_url, stylesheet, url_fetcher, self.matcher,
|
2022-04-19 01:01:50 +03:00
|
|
|
self.page_rules, font_config, counter_style)
|
2012-03-24 16:39:31 +04:00
|
|
|
|
2014-04-27 21:16:14 +04:00
|
|
|
|
2020-01-02 14:06:58 +03:00
|
|
|
class Attachment:
|
2020-05-30 02:27:13 +03:00
|
|
|
"""File attachment for a PDF document.
|
2014-04-26 01:35:43 +04:00
|
|
|
|
2019-02-22 13:34:46 +03:00
|
|
|
An instance is created in the same way as :class:`HTML`, except that the
|
|
|
|
HTML specific arguments (``encoding`` and ``media_type``) are not
|
2024-02-02 18:42:10 +03:00
|
|
|
supported.
|
2014-04-26 01:35:43 +04:00
|
|
|
|
2024-02-02 18:42:10 +03:00
|
|
|
:param str description:
|
2023-04-13 20:34:22 +03:00
|
|
|
A description of the attachment to be included in the PDF document.
|
|
|
|
May be :obj:`None`.
|
2024-02-02 18:42:10 +03:00
|
|
|
:type created: :obj:`datetime.datetime`
|
|
|
|
:param created:
|
|
|
|
Creation date and time. Default is current date and time.
|
|
|
|
:type modified: :obj:`datetime.datetime`
|
|
|
|
:param modified:
|
|
|
|
Modification date and time. Default is current date and time.
|
|
|
|
:param str relationship:
|
|
|
|
A string that represents the relationship between the attachment and
|
|
|
|
the PDF it is embedded in. Default is 'Unspecified', other common
|
|
|
|
values are defined in ISO-32000-2:2020, 7.11.3.
|
2014-04-26 01:35:43 +04:00
|
|
|
|
|
|
|
"""
|
|
|
|
def __init__(self, guess=None, filename=None, url=None, file_obj=None,
|
|
|
|
string=None, base_url=None, url_fetcher=default_url_fetcher,
|
2023-04-24 16:26:25 +03:00
|
|
|
description=None, created=None, modified=None,
|
2024-02-02 18:42:10 +03:00
|
|
|
relationship='Unspecified'):
|
2014-04-26 01:35:43 +04:00
|
|
|
self.source = _select_source(
|
2022-02-14 07:59:23 +03:00
|
|
|
guess, filename, url, file_obj, string, base_url=base_url,
|
|
|
|
url_fetcher=url_fetcher)
|
2014-04-26 01:35:43 +04:00
|
|
|
self.description = description
|
2024-02-02 18:42:10 +03:00
|
|
|
self.relationship = relationship
|
|
|
|
self.md5 = None
|
2023-04-24 16:26:25 +03:00
|
|
|
|
2024-02-02 18:42:10 +03:00
|
|
|
if created is None:
|
2023-04-24 16:26:25 +03:00
|
|
|
if filename:
|
2024-02-02 18:42:10 +03:00
|
|
|
created = datetime.fromtimestamp(getctime(filename))
|
2023-04-24 16:26:25 +03:00
|
|
|
else:
|
2024-02-02 18:42:10 +03:00
|
|
|
created = datetime.now()
|
|
|
|
if modified is None:
|
2023-04-24 16:26:25 +03:00
|
|
|
if filename:
|
2024-02-02 18:42:10 +03:00
|
|
|
modified = datetime.fromtimestamp(getmtime(filename))
|
2023-04-24 16:26:25 +03:00
|
|
|
else:
|
2024-02-02 18:42:10 +03:00
|
|
|
modified = datetime.now()
|
2024-02-12 12:41:28 +03:00
|
|
|
self.created = created
|
|
|
|
self.modified = modified
|
2014-04-26 01:35:43 +04:00
|
|
|
|
2012-02-15 21:49:37 +04:00
|
|
|
|
2013-06-20 15:58:24 +04:00
|
|
|
@contextlib.contextmanager
|
2012-03-24 16:39:31 +04:00
|
|
|
def _select_source(guess=None, filename=None, url=None, file_obj=None,
|
2017-06-30 21:12:53 +03:00
|
|
|
string=None, base_url=None, url_fetcher=default_url_fetcher,
|
|
|
|
check_css_mime_type=False):
|
2020-05-30 02:27:13 +03:00
|
|
|
"""If only one input is given, return it with normalized ``base_url``."""
|
2012-02-15 21:49:37 +04:00
|
|
|
if base_url is not None:
|
|
|
|
base_url = ensure_url(base_url)
|
|
|
|
|
2017-08-23 12:42:32 +03:00
|
|
|
selected_params = [
|
|
|
|
param for param in (guess, filename, url, file_obj, string) if
|
|
|
|
param is not None]
|
|
|
|
if len(selected_params) != 1:
|
2022-02-14 07:59:23 +03:00
|
|
|
source = ', '.join(selected_params) or 'nothing'
|
|
|
|
raise TypeError(f'Expected exactly one source, got {source}')
|
2017-09-06 17:55:21 +03:00
|
|
|
elif guess is not None:
|
2012-02-27 18:07:41 +04:00
|
|
|
if hasattr(guess, 'read'):
|
|
|
|
type_ = 'file_obj'
|
2018-08-21 17:17:00 +03:00
|
|
|
elif isinstance(guess, Path):
|
|
|
|
type_ = 'filename'
|
2012-05-31 16:38:34 +04:00
|
|
|
elif url_is_absolute(guess):
|
2012-02-27 18:07:41 +04:00
|
|
|
type_ = 'url'
|
2012-02-15 21:49:37 +04:00
|
|
|
else:
|
2012-02-27 18:07:41 +04:00
|
|
|
type_ = 'filename'
|
2013-06-20 15:58:24 +04:00
|
|
|
result = _select_source(
|
2012-07-13 14:24:55 +04:00
|
|
|
base_url=base_url, url_fetcher=url_fetcher,
|
|
|
|
check_css_mime_type=check_css_mime_type,
|
2018-01-14 03:48:17 +03:00
|
|
|
**{type_: guess})
|
2013-06-20 15:58:24 +04:00
|
|
|
with result as result:
|
|
|
|
yield result
|
2017-09-06 17:55:21 +03:00
|
|
|
elif filename is not None:
|
2012-03-24 16:39:31 +04:00
|
|
|
if base_url is None:
|
|
|
|
base_url = path2url(filename)
|
2013-06-20 15:58:24 +04:00
|
|
|
with open(filename, 'rb') as file_obj:
|
|
|
|
yield 'file_obj', file_obj, base_url, None
|
2017-09-06 17:55:21 +03:00
|
|
|
elif url is not None:
|
2013-06-20 15:58:24 +04:00
|
|
|
with fetch(url_fetcher, url) as result:
|
|
|
|
if check_css_mime_type and result['mime_type'] != 'text/css':
|
2017-07-25 14:59:56 +03:00
|
|
|
LOGGER.error(
|
2013-06-20 15:58:24 +04:00
|
|
|
'Unsupported stylesheet type %s for %s',
|
|
|
|
result['mime_type'], result['redirected_url'])
|
|
|
|
yield 'string', '', base_url, None
|
|
|
|
else:
|
2013-12-13 17:12:31 +04:00
|
|
|
proto_encoding = result.get('encoding')
|
|
|
|
if base_url is None:
|
|
|
|
base_url = result.get('redirected_url', url)
|
|
|
|
if 'string' in result:
|
|
|
|
yield 'string', result['string'], base_url, proto_encoding
|
|
|
|
else:
|
|
|
|
yield (
|
|
|
|
'file_obj', result['file_obj'], base_url,
|
|
|
|
proto_encoding)
|
2017-09-06 17:55:21 +03:00
|
|
|
elif file_obj is not None:
|
2012-02-16 16:40:29 +04:00
|
|
|
if base_url is None:
|
2012-10-05 20:50:40 +04:00
|
|
|
# filesystem file-like objects have a 'name' attribute.
|
2012-02-16 16:40:29 +04:00
|
|
|
name = getattr(file_obj, 'name', None)
|
2012-07-18 16:31:55 +04:00
|
|
|
# Some streams have a .name like '<stdin>', not a filename.
|
|
|
|
if name and not name.startswith('<'):
|
2012-02-16 16:40:29 +04:00
|
|
|
base_url = ensure_url(name)
|
2013-06-20 15:58:24 +04:00
|
|
|
yield 'file_obj', file_obj, base_url, None
|
2017-09-06 17:55:21 +03:00
|
|
|
else:
|
2020-01-10 01:33:07 +03:00
|
|
|
assert string is not None
|
|
|
|
yield 'string', string, base_url, None
|
2013-02-25 18:21:25 +04:00
|
|
|
|
|
|
|
# Work around circular imports.
|
2024-03-17 13:34:03 +03:00
|
|
|
from .css import preprocess_stylesheet # noqa: I001, E402
|
|
|
|
from .html import ( # noqa: E402
|
2023-01-23 14:38:12 +03:00
|
|
|
HTML5_UA_COUNTER_STYLE, HTML5_UA_STYLESHEET, HTML5_UA_FORM_STYLESHEET,
|
|
|
|
HTML5_PH_STYLESHEET)
|
2024-03-17 13:34:03 +03:00
|
|
|
from .document import Document, Page # noqa: E402
|