PDF: Опциональное содержимое PDF документа
В этом разделе
Опциональный контент (PDF 1.5) - это секции контента PDF документа, которые могут быть выборочно просмотрены или скрыты авторами или пользователями PDF документа. Эта возможность полезна для таких элементов, как многослойные иллюстрации, карты, многоязычные документы и т. д.
VintaSoft PDF .NET Plug-in позволяет:
- Управлять свойствами опционального контента
- Управлять свойствами группы опционального контента
- Управлять видимостью групп опционального контента
- Управлять отображением групп опционального контента
- Создать новую группу опционального контента
- Добавить несколько графических элементов в группу опционального контента.
Управление свойствами опционального контента
Доступ к свойствам опционального контента можно получить с помощью свойства
PdfDocument.OptionalContentProperties, значением которого является экземпляр класса
PdfOptionalContentProperties. Класс
PdfOptionalContentProperties позволяет:
Группа опционального контента - это набор графических элементов, которые пользователи приложений просмотра могут динамически делать видимыми или невидимыми. Группу опционального контента можно определить с помощью класса
PdfOptionalContentGroup. Класс
PdfOptionalContentGroup позволяет:
- получать или задавать строку, подходящую для представления в пользовательском интерфейсе приложения просмотра, используя свойство PdfOptionalContentGroup.Name.
- получать или задавать намерение, определяющее, какие состояния группы опционального контента учитывать и игнорировать при расчете видимости контента с помощью свойства PdfOptionalContentGroup.Intent
Конфигурация опционального контента может быть определена с помощью класса
PdfOptionalContentConfiguration и используется для управления видимостью групп опционального контента. Класс
PdfOptionalContentConfiguration предоставляет следующие свойства и методы:
Управление рендерингом групп опционального контента
Свойство
PdfDocument.OptionalContentProperties позволяет получить/задать свойства опционального контента документа. Свойство
PdfOptionalContentProperties.DefaultConfiguration позволяет получить/задать конфигурацию по умолчанию для опционального контента.
Свойство
PdfOptionalContentProperties.Configurations позволяет получить/задать доступные конфигурации опционального контента.
Свойство
PdfDocument.OptionalContentConfiguration позволяет получить/задать текущую конфигурацию опционального контента. В качестве значения свойства может быть использована только конфигурация из доступных конфигураций (свойство
PdfOptionalContentProperties.Configurations).
Вот C#/VB.NET код, который демонстрирует, как вывести документ с опциональным контентом:
/// <summary>
/// Renders a PDF document with optional content.
/// </summary>
/// <param name="pdfFilename">The PDF filename.</param>
public static void RenderPdfUsingOptonalContent(string pdfFilename)
{
// get name of output PDF file
string outputFileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pdfFilename),
System.IO.Path.GetFileNameWithoutExtension(pdfFilename));
outputFileName = outputFileName + "_{0}_{1}.tif";
// open document stream
using (System.IO.Stream documentStream =
System.IO.File.Open(pdfFilename, System.IO.FileMode.Open))
{
// create image collection, which will store pages of PDF document
using (Vintasoft.Imaging.ImageCollection documentImages =
new Vintasoft.Imaging.ImageCollection())
{
// add document pages to the image collection
documentImages.Add(documentStream);
// open PDF document
Vintasoft.Imaging.Pdf.PdfDocument document =
Vintasoft.Imaging.Pdf.PdfDocumentController.OpenDocument(documentStream);
// if document does not have optional content
if (document.OptionalContentProperties == null)
{
System.Console.WriteLine("Document does not have optional content.");
return;
}
// if PDF document has the default optional content configuration
if (document.OptionalContentProperties.DefaultConfiguration != null)
{
// set the default optional content configuration as current optional content configuration
document.OptionalContentConfiguration = document.OptionalContentProperties.DefaultConfiguration;
// render PDF pages and save them to a multipage TIFF file
SaveImages(documentImages, string.Format(outputFileName, "defaultConfig", document.OptionalContentConfiguration.Name));
}
// if PDF document has a list of optional content configurations
if (document.OptionalContentProperties.Configurations != null)
{
// for each optional content configuration
foreach (Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration config in
document.OptionalContentProperties.Configurations)
{
// set the optional content configuration as current optional content configuration
document.OptionalContentConfiguration = config;
// render PDF pages and save them to a multipage TIFF file
SaveImages(documentImages, string.Format(outputFileName, "config", config.Name));
}
}
// create custom optional content configuration
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration myConfig =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "MyConfig");
// create an empty list of optional content groups whose state should
// be set to ON when this configuration is applied
myConfig.OnGroups =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroupList(document);
// specify that optional content groups are "Off" by default
myConfig.BaseState =
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfigurationBaseState.Off;
// set custom optional content configuration as
// current optional content configuration of PDF document
document.OptionalContentConfiguration = myConfig;
// for each optional content group of PDF document
foreach (Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup
group in document.OptionalContentProperties.OptionalContentGroups)
{
// clear list of "On" groups, i.e. specify that groups must be not visible
myConfig.OnGroups.Clear();
// add group to the list of "On" groups, i.e. specify that group must be visible
myConfig.OnGroups.Add(group);
// render PDF pages and save them to a file
SaveImages(documentImages, string.Format(outputFileName, "group", group.Name));
}
// close PDF document
Vintasoft.Imaging.Pdf.PdfDocumentController.CloseDocument(document);
// free resources
documentImages.ClearAndDisposeItems();
}
}
}
/// <summary>
/// Saves images (PDF pages) to the specified file.
/// </summary>
/// <param name="images">The image collection.</param>
/// <param name="filename">The filename where image collection must be saved.</param>
private static void SaveImages(Vintasoft.Imaging.ImageCollection images, string filename)
{
// create encoder
using (Vintasoft.Imaging.Codecs.Encoders.MultipageEncoderBase encoder =
Vintasoft.Imaging.Codecs.Encoders.AvailableEncoders.CreateMultipageEncoder(filename))
{
// set rendering settings
images.SetRenderingSettings(new Vintasoft.Imaging.Codecs.Decoders.RenderingSettings(
new Vintasoft.Imaging.Resolution(300, 300)));
// specify that image collection should not be switched to new file
encoder.SaveAndSwitchSource = false;
// save images to a file
images.SaveSync(filename, encoder);
}
}
''' <summary>
''' Renders a PDF document with optional content.
''' </summary>
''' <param name="pdfFilename">The PDF filename.</param>
Public Shared Sub RenderPdfUsingOptonalContent(pdfFilename As String)
' get name of output PDF file
Dim outputFileName As String = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(pdfFilename), System.IO.Path.GetFileNameWithoutExtension(pdfFilename))
outputFileName = outputFileName & "_{0}_{1}.tif"
' open document stream
Using documentStream As System.IO.Stream = System.IO.File.Open(pdfFilename, System.IO.FileMode.Open)
' create image collection, which will store pages of PDF document
Using documentImages As New Vintasoft.Imaging.ImageCollection()
' add document pages to the image collection
documentImages.Add(documentStream)
' open PDF document
Dim document As Vintasoft.Imaging.Pdf.PdfDocument = Vintasoft.Imaging.Pdf.PdfDocumentController.OpenDocument(documentStream)
' if document does not have optional content
If document.OptionalContentProperties Is Nothing Then
System.Console.WriteLine("Document does not have optional content.")
Return
End If
' if PDF document has the default optional content configuration
If document.OptionalContentProperties.DefaultConfiguration IsNot Nothing Then
' set the default optional content configuration as current optional content configuration
document.OptionalContentConfiguration = document.OptionalContentProperties.DefaultConfiguration
' render PDF pages and save them to a multipage TIFF file
SaveImages(documentImages, String.Format(outputFileName, "defaultConfig", document.OptionalContentConfiguration.Name))
End If
' if PDF document has a list of optional content configurations
If document.OptionalContentProperties.Configurations IsNot Nothing Then
' for each optional content configuration
For Each config As Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration In document.OptionalContentProperties.Configurations
' set the optional content configuration as current optional content configuration
document.OptionalContentConfiguration = config
' render PDF pages and save them to a multipage TIFF file
SaveImages(documentImages, String.Format(outputFileName, "config", config.Name))
Next
End If
' create custom optional content configuration
Dim myConfig As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "MyConfig")
' create an empty list of optional content groups whose state should
' be set to ON when this configuration is applied
myConfig.OnGroups = New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroupList(document)
' specify that optional content groups are "Off" by default
myConfig.BaseState = Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfigurationBaseState.Off
' set custom optional content configuration as
' current optional content configuration of PDF document
document.OptionalContentConfiguration = myConfig
' for each optional content group of PDF document
For Each group As Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup In document.OptionalContentProperties.OptionalContentGroups
' clear list of "On" groups, i.e. specify that groups must be not visible
myConfig.OnGroups.Clear()
' add group to the list of "On" groups, i.e. specify that group must be visible
myConfig.OnGroups.Add(group)
' render PDF pages and save them to a file
SaveImages(documentImages, String.Format(outputFileName, "group", group.Name))
Next
' close PDF document
Vintasoft.Imaging.Pdf.PdfDocumentController.CloseDocument(document)
' free resources
documentImages.ClearAndDisposeItems()
End Using
End Using
End Sub
''' <summary>
''' Saves images (PDF pages) to the specified file.
''' </summary>
''' <param name="images">The image collection.</param>
''' <param name="filename">The filename where image collection must be saved.</param>
Private Shared Sub SaveImages(images As Vintasoft.Imaging.ImageCollection, filename As String)
' create encoder
Using encoder As Vintasoft.Imaging.Codecs.Encoders.MultipageEncoderBase = Vintasoft.Imaging.Codecs.Encoders.AvailableEncoders.CreateMultipageEncoder(filename)
' set rendering settings
images.SetRenderingSettings(New Vintasoft.Imaging.Codecs.Decoders.RenderingSettings(New Vintasoft.Imaging.Resolution(300, 300)))
' specify that image collection should not be switched to new file
encoder.SaveAndSwitchSource = False
' save images to a file
images.SaveSync(filename, encoder)
End Using
End Sub
Создание групп опционального контента. Добавление графики в группу опционального контента
Для создания группы опционального контента необходимо создать экземпляр класса
PdfOptionalContentGroup и добавить его в список
PdfOptionalContentProperties.OptionalContentGroups. При необходимости обновите свойства конфигурации контента.
Для удаления существующей группы опционального контента необходимо удалить группу из списка
PdfOptionalContentProperties.OptionalContentGroups. При необходимости обновите свойства конфигурации контента.
Графические элементы, относящиеся к группе опционального контента, могут быть определены в процессе рисования графики на PDF странице. Метод
PdfGraphics.BeginOptionalContent должен вызываться при старте блока опционального контента. Метод
PdfGraphics.EndOptionalContent должен быть вызван по завершении блока опционального контента.
Кроме того, изображение-ресурс, форму или аннотацию можно добавить в группу опционального контента или исключить из нее с помощью свойства OptionalContentGroup:
Вот C#/VB.NET код, который демонстрирует, как создать документ с опциональным контентом:
/// <summary>
/// Creates PDF document with the optional content.
/// </summary>
/// <param name="pdfFilename">The PDF filename.</param>
public static void CreateDocumentWithOptionalContent(string pdfFilename)
{
// create new PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename, Vintasoft.Imaging.Pdf.PdfFormat.Pdf_16))
{
// add empty page (A4 size)
Vintasoft.Imaging.Pdf.Tree.PdfPage page = document.Pages.Add(
Vintasoft.Imaging.PaperSizeKind.A4);
// create two optional content groups
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup layer1 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup(document, "Layer1");
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup layer2 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup(document, "Layer2");
// add optional content groups to OptionalContentProperties
document.OptionalContentProperties =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentProperties(document);
document.OptionalContentProperties.OptionalContentGroups.Add(layer1);
document.OptionalContentProperties.OptionalContentGroups.Add(layer2);
// get PdfGraphics for PDF page
using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics g = page.GetGraphics())
{
Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont font = document.FontManager.GetStandardFont(
Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman);
Vintasoft.Imaging.Pdf.Drawing.PdfBrush brush = new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(
System.Drawing.Color.Black);
Vintasoft.Imaging.Pdf.Drawing.PdfBrush brush1 = new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(
System.Drawing.Color.Green);
Vintasoft.Imaging.Pdf.Drawing.PdfBrush brush2 = new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(
System.Drawing.Color.Red);
// draw not optional content
g.DrawString("Not optional content", font, 20, brush, new System.Drawing.PointF(50, 650));
// draw optional content "Layer1"
g.BeginOptionalContent(layer1);
g.DrawString(string.Format("Optional content '{0}'", layer1.Name),
font, 25, brush1, new System.Drawing.PointF(50, 550));
g.EndOptionalContent();
// draw not optional content
g.DrawString("Not optional content", font, 30, brush, new System.Drawing.PointF(50, 450));
// draw optional content "Layer2"
g.BeginOptionalContent(layer2);
g.DrawString(string.Format("Optional content '{0}'", layer2.Name),
font, 35, brush2, new System.Drawing.PointF(50, 350));
g.EndOptionalContent();
// draw not optional content
g.DrawString("Not optional content", font, 40, brush, new System.Drawing.PointF(50, 250));
}
// create optional content configurations
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration configuration1 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer1 and Layer2");
configuration1.SetGroupVisibility(layer1, true);
configuration1.SetGroupVisibility(layer2, true);
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration configuration2 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer1");
configuration2.SetGroupVisibility(layer1, true);
configuration2.SetGroupVisibility(layer2, false);
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration configuration3 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer2");
configuration3.SetGroupVisibility(layer1, false);
configuration3.SetGroupVisibility(layer2, true);
Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration configuration4 =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "No Layers");
configuration4.SetGroupVisibility(layer1, false);
configuration4.SetGroupVisibility(layer2, false);
// create list of optional content configuration
document.OptionalContentProperties.Configurations =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfigurationList(document);
// add configurations to list
document.OptionalContentProperties.Configurations.Add(configuration1);
document.OptionalContentProperties.Configurations.Add(configuration2);
document.OptionalContentProperties.Configurations.Add(configuration3);
document.OptionalContentProperties.Configurations.Add(configuration4);
// set default configuration
document.OptionalContentProperties.DefaultConfiguration = configuration1;
// set presentation order
configuration1.PresentationOrder =
new Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentPresentationOrder(document, layer1, layer2);
// optional content panel is visible
document.DocumentViewMode = Vintasoft.Imaging.Pdf.PdfDocumentViewMode.UseOC;
// save changes in PDF document
document.SaveChanges();
}
}
''' <summary>
''' Creates PDF document with the optional content.
''' </summary>
''' <param name="pdfFilename">The PDF filename.</param>
Public Shared Sub CreateDocumentWithOptionalContent(pdfFilename As String)
' create new PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename, Vintasoft.Imaging.Pdf.PdfFormat.Pdf_16)
' add empty page (A4 size)
Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = document.Pages.Add(Vintasoft.Imaging.PaperSizeKind.A4)
' create two optional content groups
Dim layer1 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup(document, "Layer1")
Dim layer2 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentGroup(document, "Layer2")
' add optional content groups to OptionalContentProperties
document.OptionalContentProperties = New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentProperties(document)
document.OptionalContentProperties.OptionalContentGroups.Add(layer1)
document.OptionalContentProperties.OptionalContentGroups.Add(layer2)
' get PdfGraphics for PDF page
Using g As Vintasoft.Imaging.Pdf.Drawing.PdfGraphics = page.GetGraphics()
Dim font As Vintasoft.Imaging.Pdf.Tree.Fonts.PdfFont = document.FontManager.GetStandardFont(Vintasoft.Imaging.Pdf.Tree.Fonts.PdfStandardFontType.TimesRoman)
Dim brush As New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Black)
Dim brush1 As New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Green)
Dim brush2 As New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red)
' draw not optional content
g.DrawString("Not optional content", font, 20, brush, New System.Drawing.PointF(50, 650))
' draw optional content "Layer1"
g.BeginOptionalContent(layer1)
g.DrawString(String.Format("Optional content '{0}'", layer1.Name), font, 25, brush1, New System.Drawing.PointF(50, 550))
g.EndOptionalContent()
' draw not optional content
g.DrawString("Not optional content", font, 30, brush, New System.Drawing.PointF(50, 450))
' draw optional content "Layer2"
g.BeginOptionalContent(layer2)
g.DrawString(String.Format("Optional content '{0}'", layer2.Name), font, 35, brush2, New System.Drawing.PointF(50, 350))
g.EndOptionalContent()
' draw not optional content
g.DrawString("Not optional content", font, 40, brush, New System.Drawing.PointF(50, 250))
End Using
' create optional content configurations
Dim configuration1 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer1 and Layer2")
configuration1.SetGroupVisibility(layer1, True)
configuration1.SetGroupVisibility(layer2, True)
Dim configuration2 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer1")
configuration2.SetGroupVisibility(layer1, True)
configuration2.SetGroupVisibility(layer2, False)
Dim configuration3 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "Layer2")
configuration3.SetGroupVisibility(layer1, False)
configuration3.SetGroupVisibility(layer2, True)
Dim configuration4 As New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfiguration(document, "No Layers")
configuration4.SetGroupVisibility(layer1, False)
configuration4.SetGroupVisibility(layer2, False)
' create list of optional content configuration
document.OptionalContentProperties.Configurations = New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentConfigurationList(document)
' add configurations to list
document.OptionalContentProperties.Configurations.Add(configuration1)
document.OptionalContentProperties.Configurations.Add(configuration2)
document.OptionalContentProperties.Configurations.Add(configuration3)
document.OptionalContentProperties.Configurations.Add(configuration4)
' set default configuration
document.OptionalContentProperties.DefaultConfiguration = configuration1
' set presentation order
configuration1.PresentationOrder = New Vintasoft.Imaging.Pdf.Tree.OptionalContent.PdfOptionalContentPresentationOrder(document, layer1, layer2)
' optional content panel is visible
document.DocumentViewMode = Vintasoft.Imaging.Pdf.PdfDocumentViewMode.UseOC
' save changes in PDF document
document.SaveChanges()
End Using
End Sub