Lectura y adición de metadatos XMP en documentos EPS/PS con Java

Extraiga, inspeccione, añada y actualice metadatos XMP (Extensible Metadata Platform) en documentos EPS y PostScript (PS) utilizando Aspose.Page for Java. Incruste propiedades estándar de Dublin Core, estadísticas de creación del documento, detalles de derechos de autor y estructuras de metadatos personalizadas directamente en los flujos de archivos PostScript sin alterar el contenido visual subyacente de los gráficos vectoriales.

 

Aspose.Page for Java proporciona un modelo de objetos de alto rendimiento XmpHeaderConverter y XmpMetadata para extraer metadatos XMP existentes o inyectar nuevas propiedades en archivos EPS/PS.

  • Para leer información como los datos del autor, las fechas de creación, los avisos de derechos de autor y los atributos personalizados de los archivos EPS, utilice el método XmpMetadata.get().
  • Para editar campos de metadatos existentes, como los títulos de documentos o el historial de modificaciones, utilice el método XmpMetadata.set().
  • Para añadir atributos de metadatos propietarios y específicos de la empresa a archivos gráficos, utilice el método XmpMetadata.registerNamespace().

Lectura de metadatos XMP existentes de un archivo EPS

Extraiga y analice propiedades XMP estándar y definidas por el usuario de un documento EPS para inspeccionar campos de metadatos como dc:title, xmp:CreatorTool y xmp:CreateDate.

// Get XMP metadata from EPS document.
// Learn more: https://docs.aspose.com/page/java/working-with-xm-metadata-in-eps/

// Create PsDocument instance from file
PsDocument document = new PsDocument(getDataDir() + "get_input.eps");

// 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)
XmpMetadata xmp = document.getXmpMetadata();

// Get "CreatorTool" value
if (xmp.containsKey("xmp:CreatorTool"))
    System.out.println("CreatorTool: " + xmp.get("xmp:CreatorTool").toStringValue());

// Get "CreateDate" value
if (xmp.containsKey("xmp:CreateDate"))
    System.out.println("CreateDate: " + xmp.get("xmp:CreateDate").toStringValue());

// Get a width of a thumbnail image if exists
if (xmp.containsKey("xmp:Thumbnails") && xmp.get("xmp:Thumbnails").isArray()) {
    XmpValue val = xmp.get("xmp:Thumbnails").toArray()[0];
    if (val.isNamedValues() && val.toDictionary().containsKey("xmpGImg:width"))
        System.out.println("Thumbnail Width: " + val.toDictionary().get("xmpGImg:width").toInteger());
}

// Get "format" value
if (xmp.containsKey("dc:format"))
    System.out.println("Format: " + xmp.get("dc:format").toStringValue());

// Get "DocumentID" value
if (xmp.containsKey("xmpMM:DocumentID"))
    System.out.println("DocumentID: " + xmp.get("xmpMM:DocumentID").toStringValue());

Adición e inyección de nuevos metadatos XMP en un archivo EPS

Inyecte propiedades de metadatos estándar (como los esquemas Dublin Core o XMP Basic) en un documento EPS y guarde el archivo actualizado.

// Add XMP metadata to EPS document.
// Learn more: https://docs.aspose.com/page/java/working-with-xm-metadata-in-eps/

// Initialize EPS file input stream
try (FileInputStream psStream = new FileInputStream(getDataDir() + "add_input.eps")) {
    // Create PsDocument instance from stream. Given EPS file doesn't contain XMP metadata, but usual metadata does contain.
    PsDocument document = new PsDocument(psStream);

    String outputFileName = "add_xmp_metadata_out.eps";

    XmpMetadata xmp = null;

    try {
        // 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)
        xmp = document.getXmpMetadata();

        // Check metadata values extracted from PS metadata comments and set up in new XMP metadata

        // Get "CreatorTool" value
        if (xmp.containsKey("xmp:CreatorTool"))
            System.out.println("CreatorTool: " + xmp.get("xmp:CreatorTool").toStringValue());

        // Get "CreateDate" value
        if (xmp.containsKey("xmp:CreateDate"))
            System.out.println("CreateDate: " + xmp.get("xmp:CreateDate").toStringValue());

        // Get "format" value
        if (xmp.containsKey("dc:format"))
            System.out.println("Format: " + xmp.get("dc:format").toStringValue());

        // Get "title" value
        if (xmp.containsKey("dc:title"))
            System.out.println("Title: " + xmp.get("dc:title").toArray()[0].toStringValue());

        // Get "creator" value
        if (xmp.containsKey("dc:creator"))
            System.out.println("Creator: " + xmp.get("dc:creator").toArray()[0].toStringValue());

        // Get "MetadataDate" value
        if (xmp.containsKey("xmp:MetadataDate"))
            System.out.println("MetadataDate: " + xmp.get("xmp:MetadataDate").toStringValue());

        // Update MetadataDate value                
        Date metadataDate = xmp.get("xmp:MetadataDate").toDateTime();

        // Save EPS file with new XMP metadata

        // Create ouput stream
        try (FileOutputStream outPsStream = new FileOutputStream(getOutputDir() + outputFileName)) {
            // Save EPS file
            document.save(outPsStream);
        }
    } catch (IOException ex) {
    }

Adición de espacios de nombres personalizados y metadatos de matrices

Registre espacios de nombres XML específicos de la empresa y almacene tipos de datos complejos, como listas de matrices, dentro de la estructura XMP del documento.

// Add namespace in XMP metadata in EPS document.
// Learn more: https://docs.aspose.com/page/java/working-with-xm-metadata-in-eps/
	
// Initialize EPS file input stream
try (FileInputStream psStream = new FileInputStream(getDataDir() + "add_simple_props_input.eps")) {
    // Create PsDocument instance from stream
    PsDocument document = new PsDocument(psStream);
	
    String outputFileName = "add_xmp_namespace_out.eps";
	
    try {
        // 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)
        XmpMetadata xmp = document.getXmpMetadata();
	
        //Change XMP metadata values
	
        // Add new XML namespace "tmp".
        xmp.registerNamespaceURI("tmp", "http://www.some.org/schema/tmp#");
	
        // Add new string property in new namespace.
        xmp.put("tmp:newKey", new XmpValue("NewValue"));
	
        // Save EPS file with changed XMP metadata
	
        // Create ouput stream
        try (FileOutputStream outPsStream = new FileOutputStream(getOutputDir() + outputFileName)) {
            // Save EPS file
            document.save(outPsStream);
        }
    } catch (IOException ex) {
    }

Instalación y configuración

Añada Aspose.Page for Java a su Maven:

Package Manager Console Command

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java API</name>
    <url>https://repository.aspose.com/repo/</url>
</repository>

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-page</artifactId>
    <version>Latest</version>
</dependency>

Preguntas frecuentes

1. ¿Puedo extraer metadatos XMP de un archivo EPS que no contiene un encabezado XMP estándar?

Si un archivo EPS no contiene un paquete de encabezado XMP existente, PsDocument.getXmpMetadata() devuelve una estructura XmpMetadata vacía. Puede rellenarla con propiedades y llamar a document.save() para escribir un nuevo paquete XMP válido en el archivo.

2. ¿Qué esquemas XMP estándar admite Aspose.Page for Java?

Aspose.Page admite de forma nativa todos los esquemas XMP estándar, incluidos Dublin Core (dc:), XMP Basic (xmp:), XMP Rights Management (xmpRights:), XMP Media Management (xmpMM:) y el esquema Adobe PDF (pdf:).

3. ¿La actualización de los metadatos XMP vuelve a codificar o degrada los gráficos visuales del EPS?

No. Aspose.Page modifica o inserta el bloque de metadatos del encabezado XMP ubicado en el preámbulo del documento sin alterar ni volver a comprimir las formas vectoriales, los gráficos rasterizados o el código PostScript.