def write_pdf_attachment(pdf, attachment, compress):
    """Write an attachment to the PDF stream."""
    # Attachments from document links like <link> or <a> can only be URLs.
    # They're passed in as tuples
    url = None
    uncompressed_length = 0
    stream = b''
    try:
        with attachment.source as (_, source, url, _):
            if isinstance(source, str):
                source = source.encode()
            if isinstance(source, bytes):
                source = io.BytesIO(source)
            for data in iter(lambda: source.read(4096), b''):
                uncompressed_length += len(data)
                stream += data
    except URLFetchingError as exception:
        LOGGER.error('Failed to load attachment: %s', exception)
        LOGGER.debug('Error while loading attachment:', exc_info=exception)
        return
    attachment.md5 = md5(stream, usedforsecurity=False).hexdigest()

    # TODO: Use the result object from a URL fetch operation to provide more
    # details on the possible filename and MIME type.
    if attachment.name:
        filename = attachment.name
    elif url and urlsplit(url).path:
        filename = basename(unquote(urlsplit(url).path))
    else:
        filename = 'attachment.bin'
    mime_type = mimetypes.guess_type(filename, strict=False)[0]
    if not mime_type:
        mime_type = 'application/octet-stream'

    creation = pydyf.String(attachment.created.strftime('D:%Y%m%d%H%M%SZ'))
    mod = pydyf.String(attachment.modified.strftime('D:%Y%m%d%H%M%SZ'))
    file_extra = pydyf.Dictionary({
        'Type': '/EmbeddedFile',
        'Subtype': f'/{mime_type.replace("/", "#2f")}',
        'Params': pydyf.Dictionary({
            'CheckSum': f'<{attachment.md5}>',
            'Size': uncompressed_length,
            'CreationDate': creation,
            'ModDate': mod,
        })
    })
    file_stream = pydyf.Stream([stream], file_extra, compress=compress)
    pdf.add_object(file_stream)

    pdf_attachment = pydyf.Dictionary({
        'Type': '/Filespec',
        'F': pydyf.String(filename.encode(errors='ignore')),
        'UF': pydyf.String(filename),
        'EF': pydyf.Dictionary({'F': file_stream.reference}),
        'Desc': pydyf.String(attachment.description or ''),
    })
    pdf.add_object(pdf_attachment)
    return pdf_attachment
Write an attachment to the PDF stream.
weasyprint/pdf/anchors.py