Implementing PDF Content Groups with PDF Objects in C# and .NET

A content group (represented by the PdfContentGroup class) is a group of PdfContentElements that can be jointly transformed and/or clipped without affecting the rest of the content.

The following example shows how to create content groups and how deformation and clipping applied to a content group does not affect content outside of that group.

Полный код

using System;
using System.IO;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        /// <summary>
        /// Work with Content Group.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/content-groups.php
        /// </remarks>
        static void Main(string[] args)
        {
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            using (var document = new PdfDocument())
            {
                var page = document.Pages.Add();

                // Add a rectangle with a green fill whose bottom-left corner is at location (100, 450) from the bottom-left corner of the page.
                var path = page.Content.Elements.AddPath();
                path.AddRectangle(100, 450, 200, 100);
                var format = path.Format;
                format.Fill.IsApplied = true;
                format.Fill.Color = PdfColors.Green;

                // Add an outer group whose bottom-left corner is at the same location as the page's bottom-left corner.
                var outerGroup = page.Content.Elements.AddGroup();
                // Add an inner group whose bottom-left corner is at location (100, 250) from the bottom-left corner of the outer group/page.
                var innerGroup = outerGroup.Elements.AddGroup();
                innerGroup.Transform = PdfMatrix.CreateTranslation(100, 250);

                // Add a rectangle that clips its content and the content of all elements that come after it in the same group.
                // The bottom-left corner of the clipping rectangle is at location (50, -150) from the bottom-left corner of the inner group.
                // The clipping rectangle is also stroked to show that it goes over the first and the last rectangle from the main content group, but it doesn't clip them because they are in the main content group.
                var clippingPath = innerGroup.Elements.AddPath();
                clippingPath.AddRectangle(50, -150, 100, 400);
                format = clippingPath.Format;
                format.Clip.IsApplied = true;
                format.Stroke.IsApplied = true;
                format.Stroke.Width = 2;
                format.Stroke.DashPattern = PdfLineDashPatterns.Dash;

                // Add a rectangle with a red fill that gets clipped by the previous rectangle, thus making it a square.
                // The bottom-left corner is at the same location as the inner group's bottom-left corner.
                var clippedPath = innerGroup.Elements.AddPath();
                clippedPath.AddRectangle(0, 0, 200, 100);
                format = clippedPath.Format;
                format.Fill.IsApplied = true;
                format.Fill.Color = PdfColors.Red;

                // Add the same rectangle as the first one and move it down by 400 points.
                path = page.Content.Elements.AddClone(path);
                path.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -400));

                document.Save("ContentGroups.pdf");
            }

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("ContentGroups.pdf") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		''' <summary>
		''' Work with Content Group.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/content-groups.php
		''' </remarks>
		Shared Sub Main(ByVal args() As String)
			' Before starting this example, please get a free 100-day trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Using document = New PdfDocument()
				Dim page = document.Pages.Add()

				' Add a rectangle with a green fill whose bottom-left corner is at location (100, 450) from the bottom-left corner of the page.
				Dim path = page.Content.Elements.AddPath()
				path.AddRectangle(100, 450, 200, 100)
				Dim format = path.Format
				format.Fill.IsApplied = True
				format.Fill.Color = PdfColors.Green

				' Add an outer group whose bottom-left corner is at the same location as the page's bottom-left corner.
				Dim outerGroup = page.Content.Elements.AddGroup()
				' Add an inner group whose bottom-left corner is at location (100, 250) from the bottom-left corner of the outer group/page.
				Dim innerGroup = outerGroup.Elements.AddGroup()
				innerGroup.Transform = PdfMatrix.CreateTranslation(100, 250)

				' Add a rectangle that clips its content and the content of all elements that come after it in the same group.
				' The bottom-left corner of the clipping rectangle is at location (50, -150) from the bottom-left corner of the inner group.
				' The clipping rectangle is also stroked to show that it goes over the first and the last rectangle from the main content group, but it doesn't clip them because they are in the main content group.
				Dim clippingPath = innerGroup.Elements.AddPath()
				clippingPath.AddRectangle(50, -150, 100, 400)
				format = clippingPath.Format
				format.Clip.IsApplied = True
				format.Stroke.IsApplied = True
				format.Stroke.Width = 2
				format.Stroke.DashPattern = PdfLineDashPatterns.Dash

				' Add a rectangle with a red fill that gets clipped by the previous rectangle, thus making it a square.
				' The bottom-left corner is at the same location as the inner group's bottom-left corner.
				Dim clippedPath = innerGroup.Elements.AddPath()
				clippedPath.AddRectangle(0, 0, 200, 100)
				format = clippedPath.Format
				format.Fill.IsApplied = True
				format.Fill.Color = PdfColors.Red

				' Add the same rectangle as the first one and move it down by 400 points.
				path = page.Content.Elements.AddClone(path)
				path.Subpaths.Transform(PdfMatrix.CreateTranslation(0, -400))

				document.Save("ContentGroups.pdf")
			End Using

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("ContentGroups.pdf") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.