Agregar texto a archivos PS

Solución API C++ para trabajar con textos de archivos PS

 

PostScript, un potente lenguaje de descripción de páginas, ofrece control granular sobre la ubicación y el formato del texto. A continuación se presentan algunos matices clave a considerar al trabajar con texto en PostScript:

  • PostScript le permite seleccionar fuentes usando sus nombres PostScript. Las fuentes comunes como Times Roman, Helvetica y Courier suelen estar disponibles de forma predeterminada. Para garantizar una representación coherente 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 “tamaño de fuente” establece el tamaño de fuente en puntos. Para modificar los estilos de fuente, utilice operadores como setfont que especifica negrita, cursiva u otras variaciones.
  • Posicionamiento de texto: el operador “moveto” coloca 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 con cuidado.
  • Rotación y escala de texto: el operador “rotar” se puede usar para rotar el texto a un ángulo específico, y el operador “escala” se puede usar para escalar el texto hacia arriba o hacia abajo.
  • Representación de texto: PostScript admite suavizado, que suaviza los bordes del texto para mejorar la legibilidad. También puede controlar el espacio entre caracteres (kerning) y líneas (interlineados) para ajustar la apariencia del texto.

Comprender estos aspectos puede ayudar a garantizar el uso adecuado de las fuentes y una representación coherente en flujos de trabajo basados ​​en PostScript. Pero pase lo que pase, Aspose.Page le proporciona la funcionalidad para administrar las fuentes de los archivos PS fácilmente. Con esta API puedes agregar textos de diferentes colores y pinceles usando fuentes personalizadas o del sistema. Para obtener más información sobre cómo trabajar 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:

  • Aspose.Page para C++ API, que es una API de C++ de manipulación y conversión de documentos potente, rica en funciones y fácil de usar.

  • Abra el administrador de paquetes NuGet, busque Aspose.Page.Cpp e instálelo. También puede utilizar el siguiente comando desde la Consola del Administrador de paquetes.

Package Manager Console Command

    PM> Install-Package Aspose.Page.Cpp

Pasos para agregar texto a un archivo PS.

El siguiente fragmento de código demuestra cómo agregar texto usando una cadena Unicode a un documento PostScript (PS) usando la biblioteca Aspose.Page en C#. Para ver una versión más completa del ejemplo y más ejemplos, vaya a Proyecto GitHub Aspose.Page-for-C++ .

  1. Inicialice la variable dataDir con la ruta al directorio que contiene los documentos.
  2. Configure la variable FONTS_FOLDER para establecerla en la ruta de la carpeta que contiene las fuentes necesarias.
  3. Cree una secuencia de salida para el documento PostScript utilizando la clase FileStream.
  4. Especifique las opciones de guardado para el documento PostScript usando el objeto PsSaveOptions .
  5. La propiedad AdditionalFontsFolders del objeto de opciones se establece en una matriz que contiene la ruta a FONTS_FOLDER. Esto permite que el sistema ubique las fuentes requeridas en esa carpeta.
  6. Especifique el texto y su tamaño.
  7. 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.
  8. Llame al método ClosePage() en el objeto del documento, lo que indica que la página actual está completa.
  9. Utilice el método Save() para guardar los cambios realizados en el documento PS.
Agregar imágenes a 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 Qué es PS Formato de archivo

El formato PS es uno de los formatos de lenguaje de descripción de página (PDL). Es capaz de contener información gráfica y de texto en la página. Es por eso que el formato fue soportado por la mayoría de los programas de edición de imágenes. El archivo postscript en sí mismo es una especie de instrucción para las impresoras. Contiene información sobre qué y cómo imprimir desde su página.