Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Оператор — это ключевое слово PDF, указывающее на определённое действие, например, рисование графического объекта на странице. Ключевое слово оператора отличается от именованного объекта отсутствием начального символа солидус (2Fh). Операторы имеют смысл только внутри потока содержимого.
Поток содержимого — это объект потока PDF, данные которого состоят из инструкций, описывающих графические элементы, которые должны быть нарисованы на странице. Более подробную информацию об операторах PDF можно найти в спецификации PDF.
В этом разделе объясняется, как использовать операторы с Aspose.PDF. Для иллюстрации концепции выбран пример добавления изображения в PDF-файл. Чтобы добавить изображение в PDF-файл, необходимы различные операторы. В этом примере используются GSave, ConcatenateMatrix, Do и GRestore.
Чтобы добавить изображение в PDF-файл:
Следующий фрагмент кода также работает с библиотекой Aspose.PDF.Drawing.
Следующий фрагмент кода показывает, как использовать операторы PDF.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void AddImageUsingPDFOperators()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFOperators.pdf"))
{
// Set coordinates for the image placement
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
// Get the page where the image needs to be added
var page = document.Pages[1];
// Load the image into a file stream
using (var imageStream = new FileStream(dataDir + "PDFOperators.jpg", FileMode.Open))
{
// Add the image to the page's Resources collection
page.Resources.Images.Add(imageStream);
}
// Save the current graphics state using the GSave operator
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Create a rectangle and matrix for positioning the image
var rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
var matrix = new Aspose.Pdf.Matrix(new double[]
{
rectangle.URX - rectangle.LLX, 0,
0, rectangle.URY - rectangle.LLY,
rectangle.LLX, rectangle.LLY
});
// Define how the image must be placed using the ConcatenateMatrix operator
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
// Get the image from the Resources collection
var ximage = page.Resources.Images[page.Resources.Images.Count];
// Draw the image using the Do operator
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
// Restore the graphics state using the GRestore operator
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
// Save PDF document
document.Save(dataDir + "PDFOperators_out.pdf");
}
}
Этот раздел демонстрирует, как использовать операторы GSave/GRestore и оператор ContatenateMatrix для позиционирования xForm, а также оператор Do для рисования xForm на странице.
Приведённый ниже код оборачивает существующее содержимое PDF-файла парой операторов GSave/GRestore. Этот подход помогает получить начальное графическое состояние в конце существующего содержимого. Без этого подхода нежелательные преобразования могут остаться в конце цепочки существующих операторов.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void DrawXFormOnPage()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "DrawXFormOnPage.pdf"))
{
var pageContents = document.Pages[1].Contents;
// Wrap existing contents with GSave/GRestore operators to preserve graphics state
pageContents.Insert(1, new Aspose.Pdf.Operators.GSave());
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Add GSave operator to start new graphics state
pageContents.Add(new Aspose.Pdf.Operators.GSave());
// Create an XForm
var form = Aspose.Pdf.XForm.CreateNewForm(document.Pages[1], document);
document.Pages[1].Resources.Forms.Add(form);
form.Contents.Add(new Aspose.Pdf.Operators.GSave());
// Define image width and height
form.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(200, 0, 0, 200, 0, 0));
// Load image into stream
using (var imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open))
{
// Add the image to the XForm's resources
form.Resources.Images.Add(imageStream);
}
var ximage = form.Resources.Images[form.Resources.Images.Count];
// Draw the image on the XForm
form.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
form.Contents.Add(new Aspose.Pdf.Operators.GRestore());
// Place and draw the XForm at two different coordinates
// Draw the XForm at (100, 500)
pageContents.Add(new Aspose.Pdf.Operators.GSave());
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 500));
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Draw the XForm at (100, 300)
pageContents.Add(new Aspose.Pdf.Operators.GSave());
pageContents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(1, 0, 0, 1, 100, 300));
pageContents.Add(new Aspose.Pdf.Operators.Do(form.Name));
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Restore graphics state
pageContents.Add(new Aspose.Pdf.Operators.GRestore());
// Save PDF document
document.Save(dataDir + "DrawXFormOnPage_out.pdf");
}
}
Классы операторов предоставляют широкие возможности для управления PDF-файлами. Если PDF-файл содержит графику, которую невозможно удалить с помощью метода DeleteImage класса PdfContentEditor, вместо этого можно использовать классы операторов для её удаления.
Следующий фрагмент кода показывает, как удалить графику. Обратите внимание, что если PDF-файл содержит текстовые метки для графики, они могут сохраниться в PDF-файле при использовании этого подхода. Поэтому ищите альтернативные методы удаления таких изображений с помощью графических операторов.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void RemoveGraphicsObjects()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "RemoveGraphicsObjects.pdf"))
{
// Get the specific page (page 2 in this case)
var page = document.Pages[2];
// Get the operator collection from the page contents
var oc = page.Contents;
// Define the path-painting operators to be removed
var operators = new Aspose.Pdf.Operator[]
{
new Aspose.Pdf.Operators.Stroke(),
new Aspose.Pdf.Operators.ClosePathStroke(),
new Aspose.Pdf.Operators.Fill()
};
// Delete the specified operators from the page contents
oc.Delete(operators);
// Save PDF document
document.Save(dataDir + "NoGraphics_out.pdf");
}
}
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.