Partager via


Écrire du texte à un XPS OM

Cette rubrique explique comment écrire du texte dans un om XPS.

Le texte est placé dans un modèle OM XPS en créant et en mettant en forme une interface IXpsOMGlyphes , puis en ajoutant l’interface IXpsOMGlyphes à la liste des objets visuels de la page ou du canevas. Chaque interface IXpsOMGlyphes représente une exécution de glyphe, qui est une exécution continue de caractères qui partagent un format commun. Lorsqu’un élément de format de caractère (tel que le type de police ou la taille) change ou lorsqu’une ligne saute, une nouvelle interface IXpsOMGlyphes doit être créée et ajoutée à la liste des objets visuels.

Certaines des propriétés d’une exécution de glyphe peuvent être définies à l’aide des méthodes de l’interface IXpsOMGlyphes . Toutefois, certaines propriétés interagissent avec d’autres personnes et doivent être définies à l’aide d’une interface IXpsOMGlyphsEditor .

Avant d’utiliser les exemples de code suivants dans votre programme, lisez l’exclusion de responsabilité dans Common XPS Document Programming Tasks.

Exemple de code

Créer un glyphe exécuté à partir d’une chaîne

Une exécution de glyphe est généralement créée en plusieurs étapes qui incluent le chargement des ressources de police utilisées par l’exécution du glyphe, la définition d’un pinceau de remplissage, la spécification de la taille de police et l’emplacement de départ, et la définition de la chaîne Unicode.

La section suivante de l’exemple de code contient une routine qui accepte certaines variables, notamment la taille de police, la couleur et l’emplacement, et les caractères à écrire. Le code crée ensuite un glyphe, puis l’ajoute à une page. L’exemple de code suppose que l’initialisation décrite dans Initialiser un om XPS s’est produite et que le document comporte au moins une page. Pour plus d’informations sur la création d’un om XPS vide, reportez-vous à Créer un om XPS vide.

// 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;
}

Charger et créer des ressources

La création d’une interface IXpsOMGlyphes nécessite une ressource de police. Dans de nombreux cas, un bloc de texte utilise la même police et la même couleur. Par conséquent, cette section de l’exemple de code crée les interfaces de ressources de police qui seront utilisées dans les appels qui placent le texte sur la page.

    // 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.

Dessiner du texte dans une page

La dernière section de l’exemple de code crée les exécutions de glyphes pour chaque série de textes formatés de façon similaire. Pour exécuter le code dans cette section finale, l’interface xpsFactory ainsi que la ressource de police et un pinceau de couleur de texte sont nécessaires et doivent avoir été instanciés et initialisés. Dans cet exemple, la fonction décrite dans la première section est utilisée pour créer les ensembles de glyphes et les ajouter à la page.

    // 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++;
    }

étapes suivantes

Accéder au XPS OM

Dessiner des graphiques dans un XPS OM

Placer des images dans un OM XPS

Convertir un OM XPS en document XPS

Imprimer un XPS OM

utilisé dans cette section

IOpcPartUri

IXpsOMFontResource

IXpsOMGlyphes

IXpsOMGlyphsEditor

IXpsOMObjectFactory

IXpsOMPage

IXpsOMSolidColorBrush

IXpsOMVisual

IXpsOMVisualCollection

pour plus d’informations

Initialiser un XPS OM

références API pour les documents XPS

spécification de papier XML