Añadir texto a archivos PS
Solución API de C++ para trabajar con textos de archivos PS
PostScript, un potente lenguaje de descripción de páginas, ofrece un control granular sobre la ubicación y el formato del texto. Aquí hay algunos matices clave a considerar cuando se trabaja con texto en PostScript:
- PostScript le permite seleccionar fuentes utilizando sus nombres de PostScript. Las fuentes comunes como Times Roman, Helvetica y Courier suelen estar disponibles por defecto. Para garantizar un renderizado consistente en diferentes sistemas, puede incrustar fuentes directamente en su archivo PostScript. Esto es especialmente importante para fuentes personalizadas o familias de fuentes menos comunes.
- Tamaño y estilo de fuente - El operador
fontsizeestablece el tamaño de la fuente en puntos. Para modificar los estilos de fuente, utilice operadores comosetfont, que especifica negrita, cursiva u otras variaciones. - Posicionamiento de texto - El operador
movetoposiciona el cursor de texto en un punto específico de la página. Si bien PostScript no tiene operadores de alineación directa, puede lograr la alineación mediante cálculos cuidadosos. - Rotación y escalado de texto - El operador
rotatese puede usar para rotar el texto a un ángulo específico, y el operadorscalese puede usar para aumentar o disminuir el tamaño del texto. - Renderizado de texto - PostScript admite el suavizado (anti-aliasing), que suaviza los bordes del texto para una mejor legibilidad. También puede controlar el espacio entre caracteres (kerning) y líneas (leading) para ajustar la apariencia del texto.
Comprender estos aspectos puede ayudar a garantizar el uso adecuado de las fuentes y un renderizado consistente en los flujos de trabajo basados en PostScript. En cualquier caso, Aspose.Page le brinda la funcionalidad para administrar las fuentes de los archivos PS fácilmente. Con esta API, puede añadir textos de diferentes colores y pinceles utilizando fuentes personalizadas o del sistema. Para obtener más información sobre cómo tratar con archivos PS y cómo trabajar con textos de archivos PS en particular, siga la documentación.
Para insertar textos en documentos PS necesitamos:
API Aspose.Page para C++, que es una API de manipulación y conversión de documentos para C++ rica en funciones, potente y fácil de usar.
Abra el administrador de paquetes NuGet, busque Aspose.Page.Cpp e instálelo. También puede usar el siguiente comando desde la Consola del Administrador de Paquetes.
Package Manager Console Command
PM> Install-Package Aspose.Page.Cpp
Pasos para añadir texto a un archivo PS.
El fragmento de código a continuación demuestra cómo añadir texto utilizando una cadena Unicode a un documento PostScript (PS) utilizando la biblioteca Aspose.Page en C++. Para ver una versión más completa del ejemplo y más ejemplos, vaya al proyecto de GitHub de Aspose.Page-for-C++ .
- Inicialice la variable dataDir con la ruta al directorio que contiene los documentos.
- Establezca la variable FONTS_FOLDER con la ruta de la carpeta que contiene las fuentes necesarias.
- Cree un flujo de salida para el documento PostScript utilizando la clase FileStream.
- Especifique las opciones de guardado del documento PostScript utilizando el objeto PsSaveOptions .
- La propiedad AdditionalFontsFolders del objeto de opciones se establece en una matriz que contiene la ruta a FONTS_FOLDER. Esto permite que el sistema localice cualquier fuente requerida en esa carpeta.
- Especifique el texto y su tamaño.
- Cree una nueva instancia de PsDocument con el flujo de salida, las opciones y false como parámetros. Esto inicializa un nuevo documento PostScript con las opciones especificadas.
- Llame al método ClosePage() en el objeto del documento, indicando que la página actual se ha completado.
- Utilice el método Save() para guardar los cambios realizados en el documento PS.
Código C++ para añadir texto a un archivo PS
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir_WorkingWithText();
System::String FONTS_FOLDER = RunExamples::GetDataDir_Data() + u"necessary_fonts/";
//Create output stream for PostScript document
{
System::SharedPtr<System::IO::Stream> outPsStream = System::MakeObject<System::IO::FileStream>(dataDir + u"AddText_outPS.ps", System::IO::FileMode::Create);
// Clearing resources under 'using' statement
System::Details::DisposeGuard<1> __dispose_guard_0({ outPsStream});
// ------------------------------------------
try
{
//Create save options with A4 size
System::SharedPtr<PsSaveOptions> options = System::MakeObject<PsSaveOptions>();
// Set custom fonts folder. It will be added to system fonts folders for finding needed font.
options->set_AdditionalFontsFolders(System::MakeArray<System::String>({FONTS_FOLDER}));
//A text to write to PS file
System::String str = u"ABCDEFGHIJKLMNO";
int32_t fontSize = 48;
// Create new 1-paged PS Document
System::SharedPtr<PsDocument> document = System::MakeObject<PsDocument>(outPsStream, options, false);
////////////////////////////////////// Using sysem font (located in system fonts folders) for filling text //////////////////
System::SharedPtr<System::Drawing::Font> font = System::MakeObject<System::Drawing::Font>(u"Times New Roman", static_cast<float>(fontSize), System::Drawing::FontStyle::Bold);
//Fill text with default or already defined color. In given case it is black.
document->FillText(str, font, 50.0f, 100.0f);
//Fill text with Blue color.
document->FillText(str, font, 50.0f, 150.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Blue()));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Using custom font (located in custom fonts folders) for filling text /////////////////
System::SharedPtr<DrFont> drFont = ExternalFontCache::FetchDrFont(u"Palatino Linotype", static_cast<float>(fontSize), System::Drawing::FontStyle::Regular);
//Fill text with default or already defined color. In given case it is black.
document->FillText(str, drFont, 50.0f, 200.0f);
//Fill text with Blue color.
document->FillText(str, drFont, 50.0f, 250.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Blue()));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Using sysem font (located in system fonts folders) for outlining text ////////////////
//Outline text with default or already defined pen. In given case it is black colored 1-points width pen.
document->OutlineText(str, font, 50.0f, 300.0f);
//Outline text with blue-violet colored 2-points width pen.
document->OutlineText(str, font, 50.0f, 350.0f, System::MakeObject<System::Drawing::Pen>(System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_BlueViolet()), 2.0f));
//Fill text with orange color and stroke with blue colored 2-points width pen.
document->FillAndStrokeText(str, font, 50.0f, 400.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Yellow()), System::MakeObject<System::Drawing::Pen>(System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_BlueViolet()), 2.0f));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// Using custom font (located in custom fonts folders) for outlining text /////////////////
//Outline text with default or already defined pen. In given case it is black colored 1-points width pen.
document->OutlineText(str, drFont, 50.0f, 450.0f);
//Outline text with blue-violet colored 2-points width pen.
document->OutlineText(str, drFont, 50.0f, 500.0f, System::MakeObject<System::Drawing::Pen>(System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_BlueViolet()), 2.0f));
//Fill text with orange color and stroke with blue colored 2-points width pen.
document->FillAndStrokeText(str, drFont, 50.0f, 550.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Orange()), System::MakeObject<System::Drawing::Pen>(System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Blue()), 2.0f));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////// Using custom font (located in custom fonts folders) ang glyphs widths for filling text ////////
drFont = ExternalFontCache::FetchDrFont(u"Palatino Linotype", static_cast<float>(fontSize), System::Drawing::FontStyle::Regular);
//Glyphs widths
System::ArrayPtr<float> widths = System::MakeArray<float>({87, 87, 87, 87, 34, 87, 87});
//Fill ASCII text using with assigning glyphs widths.
document->FillText(u"BAMBOOK", widths, drFont, 50.0f, 600.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Blue()));
///////////////////////////// Using custom font (located in custom fonts folders) ang glyphs widths for filling unicode text //
//Glyphs widths
widths = System::MakeArray<float>({87, 34, 87, 87, 87, 87, 87});
//Fill Unicode text using with assigning glyphs widths.
document->FillText(u"ЗООПАРК", widths, drFont, 50.0f, 650.0f, System::MakeObject<System::Drawing::SolidBrush>(System::Drawing::Color::get_Orange()));
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Close current page
document->ClosePage();
//Save the document
document->Save();
}
catch(...)
{
__dispose_guard_0.SetCurrentException(std::current_exception());
}
}
PS What is PS File Format
PS (PostScript) es un lenguaje de descripción de páginas que combina texto y gráficos en un mismo archivo. Es soportado por la mayoría de editores y contiene instrucciones para que la impresora renderice la página.