使用 Python 将 XMP 元数据添加到 EPS 文件
要使用 Python 向 EPS 文件添加 XMP 元数据,您需要遵循以下步骤:
- 为输入 EPS 文件初始化输入流。
- 从先前创建的输入流创建 PsDocument 实例。
- 从 PsDocument 获取 XmpMetadata 实例。如果 EPS 文件不包含 XMP 元数据,则会创建一个新的实例,并使用 PS 元数据注释中的值进行填充,然后返回给您。
- 现在您可以查看元数据字段的值。
- 为输出 EPS 文件初始化输出流。
- 使用新的 XMP 元数据保存 EPS 文件。
以下代码片段展示了如何在 Python 中向 EPS 文件添加 XMP 元数据:
1# The path to the documents directory.
2data_dir = Util.get_data_dir_working_with_xmp_metadata_in_eps()
3# Initialize EPS file input stream
4ps_stream = open(data_dir + "add_input.eps", "rb",)
5# Create PsDocument instance from stream
6document = PsDocument(ps_stream)
7
8try:
9 # Get XMP metadata. If EPS file doesn't contain XMP metadata we get new one filled with values from PS metadata comments (%%Creator, %%CreateDate, %%Title etc)
10 xmp = document.get_xmp_metadata()
11
12 # Check metadata values extracted from PS metadata comments and set up in new XMP metadata
13
14 # Get "CreatorTool" value
15 if xmp.contains("xmp:CreatorTool"):
16 print("CreatorTool: " + xmp.get_value("xmp:CreatorTool").to_string_value())
17
18 # Get "CreateDate" value
19 if xmp.contains("xmp:CreateDate"):
20 print("CreateDate: " + xmp.get_value("xmp:CreateDate").to_string_value())
21
22 # Get "format" value
23 if xmp.contains("dc:format"):
24 print("Format: " + xmp.get_value("dc:format").to_string_value())
25
26 # Get "title" value
27 if xmp.contains("dc:title"):
28 print("Title: " + xmp.get_value("dc:title").to_array()[0].to_string_value())
29
30 # Get "creator" value
31 if xmp.contains("dc:creator"):
32 print("Creator: " + xmp.get_value("dc:creator").to_array()[0].to_string_value())
33
34 # Get "MetadataDate" value
35 if xmp.contains("xmp:MetadataDate"):
36 print("MetadataDate: " + xmp.get_value("xmp:MetadataDate").to_string_value())
37
38 # Save EPS file with new XMP metadata
39
40 # Create ouput stream
41 with open(data_dir + "add_output.eps", "wb") as out_ps_stream:
42 # Save EPS file
43 document.save(out_ps_stream)
44
45finally:
46 ps_stream.close()
您可以从 GitHub下载示例和数据文件。