Escritura de texto en un modelo de objetos XPS

En este tema, se describe cómo escribir texto en un modelo de objetos XPS.

El texto se coloca en un modelo de objetos XPS mediante la creación y el formato de una interfaz IXpsOMGlyphs y, después, la adición de la interfaz IXpsOMGlyphs a la lista de objetos visuales de la página o lienzo. Cada interfaz IXpsOMGlyphs representa una secuencia de glifos, que es una ejecución continua de caracteres que comparten un formato común. Cuando un elemento de formato de caracteres (como el tipo de fuente o el tamaño) cambia o cuando una línea se interrumpe, se debe crear y agregar una nueva interfaz IXpsOMGlyphs a la lista de objetos visuales.

Algunas de las propiedades de una secuencia de glifos se pueden establecer mediante los métodos de la interfaz IXpsOMGlyphs. Sin embargo, algunas propiedades interactúan con otras y deben establecerse mediante una interfaz IXpsOMGlyphsEditor.

Antes de usar los siguientes ejemplos de código en el programa, lea la declinación de responsabilidades en Tareas comunes de programación de documentos XPS.

Ejemplo de código

Creación de una secuencia de glifos que se ejecuta desde una cadena

Por lo general, se crea una secuencia de glifos en varios pasos. Entre estos, se incluye cargar los recursos de fuente que usa la secuencia de glifos, establecer un pincel de relleno, especificar el tamaño de fuente y la ubicación inicial, y establecer la cadena Unicode.

La siguiente sección del código de ejemplo contiene una rutina que acepta algunas variables, como el tamaño de fuente, el color y la ubicación, y los caracteres que se van a escribir. Después, el código crea una secuencia de glifos y, luego, la agrega a una página. En el código de ejemplo, se supone que se ha producido la inicialización descrita en Inicialización de un modelo de objetos XPS y que el documento tiene al menos una página. Para obtener más información sobre cómo crear un modelo de objetos XPS en blanco, consulte Crear un modelo de objetos XPS en blanco.

// Write Text to an XPS OM
HRESULT
WriteText_AddTextToPage(
            // A pre-created object factory
    __in    IXpsOMObjectFactory   *xpsFactory,
            // The font resource to use for this run
    __in    IXpsOMFontResource    *xpsFont,
            // The font size
    __in    float                 fontEmSize,
            // The solid color brush to use for the font
    __in    IXpsOMSolidColorBrush *xpsBrush,
            // The starting location of this glyph run
    __in    XPS_POINT             *origin,
            // The text to use for this run
    __in    LPCWSTR               unicodeString,
            // The page on which to write this glyph run
    __inout IXpsOMPage            *xpsPage        
)
{
    // The data type definitions are included in this function
    // for the convenience of this code example. In an actual
    // implementation they would probably belong in a header file.
    HRESULT                       hr = S_OK;
    XPS_POINT                     glyphsOrigin = {origin->x, origin->y};
    IXpsOMGlyphsEditor            *glyphsEditor = NULL;
    IXpsOMGlyphs                  *xpsGlyphs = NULL;
    IXpsOMVisualCollection        *pageVisuals = NULL;

    // Create a new Glyphs object and set its properties.
    hr = xpsFactory->CreateGlyphs(xpsFont, &xpsGlyphs);
    hr = xpsGlyphs->SetOrigin(&glyphsOrigin);
    hr = xpsGlyphs->SetFontRenderingEmSize(fontEmSize);
    hr = xpsGlyphs->SetFillBrushLocal(xpsBrush);

    // Some properties are inter-dependent so they
    //    must be changed by using a GlyphsEditor.
    hr = xpsGlyphs->GetGlyphsEditor(&glyphsEditor);
    hr = glyphsEditor->SetUnicodeString(unicodeString);
    hr = glyphsEditor->ApplyEdits();

    // Add the new Glyphs object to the page
    hr = xpsPage->GetVisuals(&pageVisuals);
    hr = pageVisuals->Append(xpsGlyphs);

    // Release interface pointers.
    if (NULL != xpsGlyphs) xpsGlyphs->Release();
    if (NULL != glyphsEditor) glyphsEditor->Release();
    if (NULL != pageVisuals) pageVisuals->Release();

    return hr;
}

Carga y creación de recursos

La creación de una interfaz IXpsOMGlyphs requiere un recurso de fuente. En muchos casos, un bloque de texto usa la misma fuente y color. Por lo tanto, esta sección del ejemplo de código creará las interfaces de recursos de fuente que se usarán en las llamadas que colocan el texto en la página.

    // fontFileName is the name of the font file and it 
    //  is defined outside of this example.

    HRESULT                       hr = S_OK;

    GUID                          fontNameGuid;
    WCHAR                         guidString[128] = {0};
    WCHAR                         uriString[256] = {0};

    IStream                       *fontStream  = NULL;
    IOpcPartUri                   *fontUri = NULL;
    IXpsOMFontResource            *fontResource = NULL;
    IXpsOMVisualCollection        *pageVisuals = NULL;
    IXpsOMPage                    *page = NULL;
    IXpsOMVisual                  *canvasVisual = NULL;
    IXpsOMSolidColorBrush         *xpsTextColor = NULL;
    XPS_COLOR                     xpsColorBodyText;
 
    // Create font stream.
    hr = xpsFactory->CreateReadOnlyStreamOnFile ( 
        fontFileName, &fontStream );
    
    // Create new obfuscated part name for this resource using a GUID.
    hr = CoCreateGuid( &fontNameGuid );
    hr = StringFromGUID2( 
            fontNameGuid, 
            guidString, 
            ARRAYSIZE(guidString));

    // Create a URI string for this font resource that will place 
    //  the font part in the /Resources/Fonts folder of the package.
    wcscpy_s(uriString, ARRAYSIZE(uriString), L"/Resources/Fonts/");

    // Create the part name using the GUID string as the name and 
    //  ".odttf" as the extension GUID string start and ends with 
    //  curly braces so they are removed.
    wcsncat_s(uriString, ARRAYSIZE(uriString), 
        guidString + 1, wcslen(guidString) - 2); 
    wcscat_s(uriString, ARRAYSIZE(uriString), L".odttf");

    // Create the font URI interface.
    hr = xpsFactory->CreatePartUri(
        uriString,
        &fontUri);
    // Create the font resource.
    hr = xpsFactory->CreateFontResource(
        fontStream,
        XPS_FONT_EMBEDDING_OBFUSCATED,
        fontUri,
        FALSE,     // isObfSourceStream
        &fontResource);
    if (NULL != fontUri) fontUri->Release();

    // Create the brush to use for the font.
    xpsColorBodyText.colorType = XPS_COLOR_TYPE_SRGB;
    xpsColorBodyText.value.sRGB.alpha = 0xFF;
    xpsColorBodyText.value.sRGB.red = 0x00;
    xpsColorBodyText.value.sRGB.green = 0x00;
    xpsColorBodyText.value.sRGB.blue = 0x00;

    hr = xpsFactory->CreateSolidColorBrush( 
        &xpsColorBodyText,
        NULL, // This color type does not use a color profile resource.             
        &xpsTextColor);

    // xpsTextColor is released after it has been used.

Dibujar texto en una página

La sección final del código de ejemplo crea las secuencias de glifos para cada ejecución de texto con formato similar. Para ejecutar el código de esta sección final, la interfaz xpsFactory, así como el recurso de fuente y un pincel de color de texto son necesarios y se deben haber creado instancias y haber inicializado. En este ejemplo, la función descrita en la primera sección se usa para crear las secuencias de glifos y agregarlas a la página.

    // The following interfaces are created outside of this example.

    // The page on which to place the text.
    IXpsOMPage                *page = NULL;

    // The object factory used by this program.
    IXpsOMObjectFactory       *xpsFactory = NULL;

    // The font resource created in the previous snippet.
    IXpsOMFontResource        *fontResource = NULL;

    // The color brush created in the previous snippet.
    IXpsOMSolidColorBrush     *xpsTextColor = NULL;

    // The following variables are defined outside of this example.

    // An array of pointers to the Unicode strings to write.
    LPCWSTR                   *textRuns = NULL;

    // An array of start points that correspond to the 
    //    strings in textRuns.
    XPS_POINT                 *startPoints = NULL;

    // The number of text runs to add to the page.
    UINT32                    numRuns = 0;            

    HRESULT                   hr = S_OK;

    FLOAT                     fontSize = 7.56f;
    UINT32                    thisRun;

    // Add all the text runs to the page.
    thisRun = 0;
    while (thisRun < numRuns) {  
        hr = WriteText_AddTextToPage(
            xpsFactory, 
            fontResource,
            fontSize,
            xpsTextColor,
            &startPoints[thisRun],
            textRuns[thisRun],
            page);
        thisRun++;
    }

Pasos siguientes

Navegar por el OM XPS

Dibujar gráficos en un OM XPS

Colocar imágenes en un OM XPS

Escribir un OM XPS en un documento XPS

Imprimir un OM XPS

Usado en esta sección

IOpcPartUri

IXpsOMFontResource

IXpsOMGlyphs

IXpsOMGlyphsEditor

IXpsOMObjectFactory

IXpsOMPage

IXpsOMSolidColorBrush

IXpsOMVisual

IXpsOMVisualCollection

Para obtener más información

Inicializar un OM XPS

Referencia de la API de documentos XPS

XML Paper Specification