Create or update an OCMD object in a PDF document. Args: xref: (int) 0 for creating a new object, otherwise update existing one. ocgs: (list) OCG xref numbers, which shall be subject to 'policy'. policy: one of 'AllOn', 'AllOff', 'AnyOn', 'AnyOff' (any ca
(
doc: 'Document',
xref: int = 0,
ocgs: typing.Union[list, None] = None,
policy: OptStr = None,
ve: typing.Union[list, None] = None,
)
| 6976 | return None |
| 6977 | |
| 6978 | def set_ocmd( |
| 6979 | doc: 'Document', |
| 6980 | xref: int = 0, |
| 6981 | ocgs: typing.Union[list, None] = None, |
| 6982 | policy: OptStr = None, |
| 6983 | ve: typing.Union[list, None] = None, |
| 6984 | ) -> int: |
| 6985 | """Create or update an OCMD object in a PDF document. |
| 6986 | |
| 6987 | Args: |
| 6988 | xref: (int) 0 for creating a new object, otherwise update existing one. |
| 6989 | ocgs: (list) OCG xref numbers, which shall be subject to 'policy'. |
| 6990 | policy: one of 'AllOn', 'AllOff', 'AnyOn', 'AnyOff' (any casing). |
| 6991 | ve: (list) visibility expression. Use instead of 'ocgs' with 'policy'. |
| 6992 | |
| 6993 | Returns: |
| 6994 | Xref of the created or updated OCMD. |
| 6995 | """ |
| 6996 | |
| 6997 | all_ocgs = set(doc.get_ocgs().keys()) |
| 6998 | |
| 6999 | def ve_maker(ve): |
| 7000 | if type(ve) not in (list, tuple) or len(ve) < 2: |
| 7001 | raise ValueError(f"bad 've' format: {ve}") |
| 7002 | if ve[0].lower() not in ("and", "or", "not"): |
| 7003 | raise ValueError(f"bad operand: {ve[0]}") |
| 7004 | if ve[0].lower() == "not" and len(ve) != 2: |
| 7005 | raise ValueError(f"bad 've' format: {ve}") |
| 7006 | item = f"[/{ve[0].title()}" |
| 7007 | for x in ve[1:]: |
| 7008 | if type(x) is int: |
| 7009 | if x not in all_ocgs: |
| 7010 | raise ValueError(f"bad OCG {x}") |
| 7011 | item += f" {x} 0 R" |
| 7012 | else: |
| 7013 | item += f" {ve_maker(x)}" |
| 7014 | item += "]" |
| 7015 | return item |
| 7016 | |
| 7017 | text = "<</Type/OCMD" |
| 7018 | |
| 7019 | if ocgs and type(ocgs) in (list, tuple): # some OCGs are provided |
| 7020 | s = set(ocgs).difference(all_ocgs) # contains illegal xrefs |
| 7021 | if s != set(): |
| 7022 | msg = f"bad OCGs: {s}" |
| 7023 | raise ValueError(msg) |
| 7024 | text += "/OCGs[" + " ".join(map(lambda x: f"{x} 0 R", ocgs)) + "]" |
| 7025 | |
| 7026 | if policy: |
| 7027 | policy = str(policy).lower() |
| 7028 | pols = { |
| 7029 | "anyon": "AnyOn", |
| 7030 | "allon": "AllOn", |
| 7031 | "anyoff": "AnyOff", |
| 7032 | "alloff": "AllOff", |
| 7033 | } |
| 7034 | if policy not in ("anyon", "allon", "anyoff", "alloff"): |
| 7035 | raise ValueError(f"bad policy: {policy}") |