Update the PDF /Info object. Args: m: a dictionary like doc.metadata.
(doc: 'Document', m: dict = None)
| 6893 | return True |
| 6894 | |
| 6895 | def set_metadata(doc: 'Document', m: dict = None) -> None: |
| 6896 | """Update the PDF /Info object. |
| 6897 | |
| 6898 | Args: |
| 6899 | m: a dictionary like doc.metadata. |
| 6900 | """ |
| 6901 | if not doc.is_pdf: |
| 6902 | raise ValueError("is no PDF") |
| 6903 | if doc.is_closed or doc.is_encrypted: |
| 6904 | raise ValueError("document closed or encrypted") |
| 6905 | if m is None: |
| 6906 | m = {} |
| 6907 | elif type(m) is not dict: |
| 6908 | raise ValueError("bad metadata") |
| 6909 | keymap = { |
| 6910 | "author": "Author", |
| 6911 | "producer": "Producer", |
| 6912 | "creator": "Creator", |
| 6913 | "title": "Title", |
| 6914 | "format": None, |
| 6915 | "encryption": None, |
| 6916 | "creationDate": "CreationDate", |
| 6917 | "modDate": "ModDate", |
| 6918 | "subject": "Subject", |
| 6919 | "keywords": "Keywords", |
| 6920 | "trapped": "Trapped", |
| 6921 | } |
| 6922 | valid_keys = set(keymap.keys()) |
| 6923 | diff_set = set(m.keys()).difference(valid_keys) |
| 6924 | if diff_set != set(): |
| 6925 | msg = f"bad dict key(s): {diff_set}" |
| 6926 | raise ValueError(msg) |
| 6927 | |
| 6928 | t, temp = doc.xref_get_key(-1, "Info") |
| 6929 | if t != "xref": |
| 6930 | info_xref = 0 |
| 6931 | else: |
| 6932 | info_xref = int(temp.replace("0 R", "")) |
| 6933 | |
| 6934 | if m == {} and info_xref == 0: # nothing to do |
| 6935 | return |
| 6936 | |
| 6937 | if info_xref == 0: # no prev metadata: get new xref |
| 6938 | info_xref = doc.get_new_xref() |
| 6939 | doc.update_object(info_xref, "<<>>") # fill it with empty object |
| 6940 | doc.xref_set_key(-1, "Info", f"{info_xref} 0 R") |
| 6941 | elif m == {}: # remove existing metadata |
| 6942 | doc.xref_set_key(-1, "Info", "null") |
| 6943 | doc.init_doc() |
| 6944 | return |
| 6945 | |
| 6946 | for key, val in [(k, v) for k, v in m.items() if keymap[k] is not None]: |
| 6947 | pdf_key = keymap[key] |
| 6948 | if not bool(val) or val in ("none", "null"): |
| 6949 | val = "null" |
| 6950 | else: |
| 6951 | val = get_pdf_str(val) |
| 6952 | doc.xref_set_key(info_xref, pdf_key, val) |