Межоперационные действия (операции между пакетами) в пакете XPS

Управляйте страницами, цветами и глифами в пакете XPS с помощью C++

 

API Aspose.Page для C++ предлагает отдельную библиотеку для работы с файлами XPS, позволяя вам обрабатывать их как отдельный формат. Эта библиотека может похвастаться множеством полезных функций, включая объединение документов XPS, преобразование их в другие форматы и манипулирование графикой внутри них.

Одним из ключевых аспектов файлов XPS является их способность содержать несколько файлов в одном документе. В результате библиотека Aspose.Page XPS обеспечивает функциональность для управления этими внутренними файлами и их страницами. Эти операции, известные как «операции между пакетами (cross-package operations)», включают в себя манипулирование контентом в различных документах XPS.

В этом разделе будут подробно рассмотрены конкретные примеры операций между пакетами, такие как управление страницами в одном документе XPS и добавление текста (глифов) определенных цветов.

Но чтобы попробовать функциональность, сначала вам нужно получить решение:

  • Откройте диспетчер пакетов NuGet, найдите Aspose.Page и установите его. Вы также можете использовать следующую команду в консоли диспетчера пакетов (Package Manager Console).

Шаги по управлению страницами в пакете XPS (C++).

  1. Установите путь к каталогу документов.
  2. Создайте файл XPS с помощью класса XpsDocument Class .
  3. Чтобы вставить активную страницу из одного документа в начало другого документа, используйте метод InsertPage() .
  4. Чтобы вставить активную страницу из одного документа в конец другого документа, используйте метод AddPage() .
  5. Чтобы удалить пустую страницу, используйте метод RemovePage() .
  6. Чтобы переместить страницу из одного документа в другой, используйте методы InsertPage() и SelectActivePage() .
  7. Сохраните измененные документы XPS с помощью метода XPsDocument.Save .
Управление страницами
    // The path to the documents directory.
    System::String dataDir = RunExamples::GetDataDir_WorkingWithCrossPackageOperations();
    
    // Create the first XPS Document
    System::SharedPtr<XpsDocument> doc1 = System::MakeObject<XpsDocument>(dataDir + u"input1.xps");
    
    // Create the second XPS Document
    System::SharedPtr<XpsDocument> doc2 = System::MakeObject<XpsDocument>(dataDir + u"input2.xps");
    
    // Create the third XPS Document
    System::SharedPtr<XpsDocument> doc3 = System::MakeObject<XpsDocument>(dataDir + u"input3.xps");
    
    // Create the fourth XPS Document
    System::SharedPtr<XpsDocument> doc4 = System::MakeObject<XpsDocument>();
    
    // Insert active page (1 in this case) from the second document to the beginning of the fourth document
    doc4->InsertPage(1, doc2->get_Page(), false);
    
    // Insert active page (1 in this case) from the third document to the end of the fourth document
    doc4->AddPage(doc3->get_Page(), false);
    
    // Remove page 2 from the fourth document. This is an empty page that was created when document has been created.
    doc4->RemovePageAt(2);
    
    // Insert page 3 from the first document to the second postion of the fourth document
    doc4->InsertPage(2, doc1->SelectActivePage(3), false);
    
    // Save the fourth XPS document
    doc4->Save(dataDir + u"output/" + u"out.xps");

Шаги для добавления клона глифа в пакете XPS (C++).

  1. Установите путь к каталогу документов.
  2. Откройте поток (stream) файла XPS.
  3. Создайте файл XPS с помощью класса XpsDocument Class.
  4. Добавьте глифы в документ с помощью метода AddGlyphs() .
  5. Создайте второй файл XPS с помощью класса XpsDocument Class.
  6. Чтобы клонировать глиф из первого файла во второй, используйте методы Add() и Clone() .
  7. Сохраните оба документа XPS с помощью метода XPsDocument.Save().
Добавить клон глифа и изменить цвет
    // The path to the documents directory.
    System::String dataDir = RunExamples::GetDataDir_WorkingWithCrossPackageOperations();
    
    // Create the first XPS Document
    System::SharedPtr<XpsDocument> doc1 = System::MakeObject<XpsDocument>();
    
    // Add glyphs to the first document
    System::SharedPtr<XpsGlyphs> glyphs = doc1->AddGlyphs(u"Times New Roman", 200.0f, System::Drawing::FontStyle::Bold, 50.0f, 250.0f, u"Test");
    
    // Fill glyphs in the first document with one color
    glyphs->set_Fill(doc1->CreateSolidColorBrush(System::Drawing::Color::get_Green()));
    
    // Create the second XPS Document
    System::SharedPtr<XpsDocument> doc2 = System::MakeObject<XpsDocument>();
    
    // Add glyphs cloned from the one's from the first document
    glyphs = doc2->Add<System::SharedPtr<XpsGlyphs>>(glyphs->Clone());
    
    // Fill glyphs in the second document with another color
    (System::ExplicitCast<Aspose::Page::XPS::XpsModel::XpsSolidColorBrush>(glyphs->get_Fill()))->set_Color(doc2->CreateColor(System::Drawing::Color::get_Red()));
    
    // Save the first XPS document
    doc1->Save(dataDir + u"output/" + u"out1.xps");
    
    // Save the second XPS document
    doc2->Save(dataDir + u"output/" + u"out2.xps");

Шаги по добавлению глифа, заполненного изображением, в C++.

  1. Установите путь к каталогу документов.
  2. Откройте поток файла XPS.
  3. Создайте файл XPS с помощью класса XpsDocument Class.
  4. Добавьте глифы в документ с помощью метода AddGlyphs().
  5. Чтобы заполнить глифы с помощью кисти изображения (image brush), используйте метод CreateImageBrush() .
  6. Создайте второй файл XPS с помощью класса XpsDocument Class.
  7. Добавьте глифы со шрифтом из первого документа во второй документ с помощью метода AddGlyphs().
  8. Создайте кисть изображения из заливки первого документа и заполните глифы во втором документе с помощью метода CreateImageBrush().
  9. Сохраните оба документа XPS с помощью метода XPsDocument.Save().
Добавить глиф, заполненный изображением, и внешнее изображение
    // The path to the documents directory.
    System::String dataDir = RunExamples::GetDataDir_WorkingWithCrossPackageOperations();
    
    // Create the first XPS Document
    System::SharedPtr<XpsDocument> doc1 = System::MakeObject<XpsDocument>();
    
    // Add glyphs to the first document
    System::SharedPtr<XpsGlyphs> glyphs1 = doc1->AddGlyphs(u"Times New Roman", 200.0f, System::Drawing::FontStyle::Bold, 50.0f, 250.0f, u"Test");
    
    // Fill the glyphs with an image brush
    glyphs1->set_Fill(doc1->CreateImageBrush(dataDir + u"R08SY_NN.tif", System::Drawing::RectangleF(0.f, 0.f, 128.f, 192.f), System::Drawing::RectangleF(0.f, 0.f, 64.f, 96.f)));
    (System::ExplicitCast<Aspose::Page::XPS::XpsModel::XpsImageBrush>(glyphs1->get_Fill()))->set_TileMode(Aspose::Page::XPS::XpsModel::XpsTileMode::Tile);
    
    // Create the second XPS Document
    System::SharedPtr<XpsDocument> doc2 = System::MakeObject<XpsDocument>();
    
    // Add glyphs with the font from the first document to the second document
    System::SharedPtr<XpsGlyphs> glyphs2 = doc2->AddGlyphs(glyphs1->get_Font(), 200.0f, 50.0f, 250.0f, u"Test");
    
    // Create an image brush from the fill of the the first document and fill glyphs in the second document
    glyphs2->set_Fill(doc2->CreateImageBrush((System::ExplicitCast<Aspose::Page::XPS::XpsModel::XpsImageBrush>(glyphs1->get_Fill()))->get_Image(), System::Drawing::RectangleF(0.f, 0.f, 128.f, 192.f), System::Drawing::RectangleF(0.f, 0.f, 128.f, 192.f)));
    (System::ExplicitCast<Aspose::Page::XPS::XpsModel::XpsImageBrush>(glyphs2->get_Fill()))->set_TileMode(Aspose::Page::XPS::XpsModel::XpsTileMode::Tile);
    
    // Save the first XPS document
    doc1->Save(dataDir + u"output/" + u"out1.xps");
    
    // Save the second XPS document
    doc2->Save(dataDir + u"output/" + u"out2.xps");

XPS Формат файла XPS

XPS (XML Paper Specification) — альтернативный Microsoft формат PDF, основанный на XML/HTML, сохраняет макет независимо от платформы.