Создание тегированного PDF с использованием C#
Создание тегированного PDF означает добавление (или создание) определенных элементов в документ, которые позволят документу пройти проверку на соответствие с требованиями PDF/UA. Эти элементы часто называются элементами структуры.
Следующие фрагменты кода также работают с библиотекой Aspose.PDF.Drawing .
Создание тегированного PDF (Простой сценарий)
Для создания элементов структуры в тегированном PDF документе Aspose.PDF предлагает методы для создания элементов структуры с использованием интерфейса ITaggedContent . Следующий фрагмент кода показывает, как создать тегированный PDF, который содержит 2 элемента: заголовок и абзац.
.NET Core 3.1
Copy
private static void CreateTaggedPdfDocument01 ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using ( var document = new Aspose . Pdf . Document ())
{
Aspose . Pdf . Tagged . ITaggedContent taggedContent = document . TaggedContent ;
var rootElement = taggedContent . RootElement ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
Aspose . Pdf . LogicalStructure . HeaderElement mainHeader = taggedContent . CreateHeaderElement ();
mainHeader . SetText ( "Main Header" );
Aspose . Pdf . LogicalStructure . ParagraphElement paragraphElement = taggedContent . CreateParagraphElement ();
paragraphElement . SetText ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. " +
"Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet" +
"nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus." +
"Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat" +
"sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper" +
"pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus" +
"ac iaculis eget, tempus et magna. Sed non consectetur elit. Sed vulputate, quam sed lacinia luctus," +
"ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus." );
rootElement . AppendChild ( mainHeader );
rootElement . AppendChild ( paragraphElement );
document . Save ( dataDir + "TaggedPdfDocument_out.pdf" );
}
}
.NET 8
Copy
private static void CreateTaggedPdfDocument01 ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using var document = new Aspose . Pdf . Document ();
Aspose . Pdf . Tagged . ITaggedContent taggedContent = document . TaggedContent ;
var rootElement = taggedContent . RootElement ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
Aspose . Pdf . LogicalStructure . HeaderElement mainHeader = taggedContent . CreateHeaderElement ();
mainHeader . SetText ( "Main Header" );
Aspose . Pdf . LogicalStructure . ParagraphElement paragraphElement = taggedContent . CreateParagraphElement ();
paragraphElement . SetText ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. " +
"Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet" +
"nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus." +
"Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat" +
"sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper" +
"pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus" +
"ac iaculis eget, tempus et magna. Sed non consectetur elit. Sed vulputate, quam sed lacinia luctus," +
"ipsum nibh fringilla purus, vitae posuere risus odio id massa. Cras sed venenatis lacus." );
rootElement . AppendChild ( mainHeader );
rootElement . AppendChild ( paragraphElement );
document . Save ( dataDir + "TaggedPdfDocument_out.pdf" );
}
Мы получим следующий документ после создания:
Создание тегированного PDF с вложенными элементами (Создание дерева элементов структуры)
В некоторых случаях нам нужно создать более сложную структуру, например, разместить цитаты в абзаце.
Для создания дерева элементов структуры мы должны использовать метод AppendChild .
Следующий фрагмент кода показывает, как создать дерево элементов структуры тегированного PDF документа:
.NET Core 3.1
Copy
private static void CreateTaggedPdfDocument02 ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using ( var document = new Aspose . Pdf . Document ())
{
Aspose . Pdf . Tagged . ITaggedContent taggedContent = document . TaggedContent ;
var rootElement = taggedContent . RootElement ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
Aspose . Pdf . LogicalStructure . HeaderElement header1 = taggedContent . CreateHeaderElement ( 1 );
header1 . SetText ( "Header Level 1" );
Aspose . Pdf . LogicalStructure . ParagraphElement paragraphWithQuotes = taggedContent . CreateParagraphElement ();
paragraphWithQuotes . StructureTextState . Font = Aspose . Pdf . Text . FontRepository . FindFont ( "Calibri" );
paragraphWithQuotes . AdjustPosition ( new Aspose . Pdf . Tagged . PositionSettings
{
Margin = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 )
});
Aspose . Pdf . LogicalStructure . SpanElement spanElement1 = taggedContent . CreateSpanElement ();
spanElement1 . SetText ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit. " );
Aspose . Pdf . LogicalStructure . QuoteElement quoteElement = taggedContent . CreateQuoteElement ();
quoteElement . SetText ( "Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa." );
quoteElement . StructureTextState . FontStyle = Aspose . Pdf . Text . FontStyles . Bold | Aspose . Pdf . Text . FontStyles . Italic ;
Aspose . Pdf . LogicalStructure . SpanElement spanElement2 = taggedContent . CreateSpanElement ();
spanElement2 . SetText ( " Sed non consectetur elit." );
paragraphWithQuotes . AppendChild ( spanElement1 );
paragraphWithQuotes . AppendChild ( quoteElement );
paragraphWithQuotes . AppendChild ( spanElement2 );
rootElement . AppendChild ( header1 );
rootElement . AppendChild ( paragraphWithQuotes );
document . Save ( dataDir + "TaggedPdfDocument_out.pdf" );
}
}
.NET 8
Copy
private static void CreateTaggedPdfDocument02 ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using var document = new Aspose . Pdf . Document ();
Aspose . Pdf . Tagged . ITaggedContent taggedContent = document . TaggedContent ;
var rootElement = taggedContent . RootElement ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
Aspose . Pdf . LogicalStructure . HeaderElement header1 = taggedContent . CreateHeaderElement ( 1 );
header1 . SetText ( "Header Level 1" );
Aspose . Pdf . LogicalStructure . ParagraphElement paragraphWithQuotes = taggedContent . CreateParagraphElement ();
paragraphWithQuotes . StructureTextState . Font = Aspose . Pdf . Text . FontRepository . FindFont ( "Calibri" );
paragraphWithQuotes . AdjustPosition ( new Aspose . Pdf . Tagged . PositionSettings
{
Margin = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 )
});
Aspose . Pdf . LogicalStructure . SpanElement spanElement1 = taggedContent . CreateSpanElement ();
spanElement1 . SetText ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec lectus ac sem faucibus imperdiet. Sed ut erat ac magna ullamcorper hendrerit. Cras pellentesque libero semper, gravida magna sed, luctus leo. Fusce lectus odio, laoreet nec ullamcorper ut, molestie eu elit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lacinia sit amet elit ac consectetur. Donec cursus condimentum ligula, vitae volutpat sem tristique eget. Nulla in consectetur massa. Vestibulum vitae lobortis ante. Nulla ullamcorper pellentesque justo rhoncus accumsan. Mauris ornare eu odio non lacinia. Aliquam massa leo, rhoncus ac iaculis eget, tempus et magna. Sed non consectetur elit. " );
Aspose . Pdf . LogicalStructure . QuoteElement quoteElement = taggedContent . CreateQuoteElement ();
quoteElement . SetText ( "Sed vulputate, quam sed lacinia luctus, ipsum nibh fringilla purus, vitae posuere risus odio id massa." );
quoteElement . StructureTextState . FontStyle = Aspose . Pdf . Text . FontStyles . Bold | Aspose . Pdf . Text . FontStyles . Italic ;
Aspose . Pdf . LogicalStructure . SpanElement spanElement2 = taggedContent . CreateSpanElement ();
spanElement2 . SetText ( " Sed non consectetur elit." );
paragraphWithQuotes . AppendChild ( spanElement1 );
paragraphWithQuotes . AppendChild ( quoteElement );
paragraphWithQuotes . AppendChild ( spanElement2 );
rootElement . AppendChild ( header1 );
rootElement . AppendChild ( paragraphWithQuotes );
document . Save ( dataDir + "TaggedPdfDocument_out.pdf" );
}
Мы получим следующий документ после создания:
Стилизация структуры текста
Для стилизации структуры текста в тегированном PDF документе Aspose.PDF предлагает свойства Font , FontSize , FontStyle и ForegroundColor класса StructureTextState . Следующий фрагмент кода показывает, как стилизовать структуру текста в тегированном PDF документе:
Иллюстрация элементов структуры
Для иллюстрации элементов структуры в тегированном PDF документе Aspose.PDF предлагает класс IllustrationElement . Следующий фрагмент кода показывает, как иллюстрировать элементы структуры в тегированном PDF документе:
Проверка тегированного PDF
Aspose.PDF for .NET предоставляет возможность проверять соответствие PDF/UA тегированного PDF. Валидация стандарта PDF/UA поддерживает:
Проверки для XObjects.
Проверки для Actions.
Проверки для необязательного контента.
Проверки для встроенных файлов.
Проверки для полей Acroform (Проверка естественного языка и альтернативного имени и цифровых подписей).
Проверки для полей формы XFA.
Проверки для настроек безопасности.
Проверки для навигации.
Проверки для аннотаций.
Ниже приведен фрагмент кода, который показывает, как проверить тегированный PDF документ. Соответствующие проблемы будут отображены в XML отчете.
Настройка позиции структуры текста
Следующий фрагмент кода показывает, как настроить позицию структуры текста в тегированном PDF документе:
.NET Core 3.1
Copy
private static void AdjustPosition ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using ( var document = new Aspose . Pdf . Document ())
{
var taggedContent = document . TaggedContent ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
var p = taggedContent . CreateParagraphElement ();
taggedContent . RootElement . AppendChild ( p );
p . SetText ( "Text." );
p . AdjustPosition ( new Aspose . Pdf . Tagged . PositionSettings
{
HorizontalAlignment = Aspose . Pdf . HorizontalAlignment . None ,
Margin = new Aspose . Pdf . MarginInfo
{
Left = 300 ,
Right = 0 ,
Top = 20 ,
Bottom = 0
},
VerticalAlignment = Aspose . Pdf . VerticalAlignment . None ,
IsFirstParagraphInColumn = false ,
IsKeptWithNext = false ,
IsInNewPage = false ,
IsInLineParagraph = false
});
document . Save ( dataDir + "AdjustTextPosition_out.pdf" );
}
}
.NET 8
Copy
private static void AdjustPosition ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using var document = new Aspose . Pdf . Document ();
var taggedContent = document . TaggedContent ;
taggedContent . SetTitle ( "Tagged Pdf Document" );
taggedContent . SetLanguage ( "en-US" );
var p = taggedContent . CreateParagraphElement ();
taggedContent . RootElement . AppendChild ( p );
p . SetText ( "Text." );
p . AdjustPosition ( new Aspose . Pdf . Tagged . PositionSettings
{
HorizontalAlignment = Aspose . Pdf . HorizontalAlignment . None ,
Margin = new Aspose . Pdf . MarginInfo
{
Left = 300 ,
Right = 0 ,
Top = 20 ,
Bottom = 0
},
VerticalAlignment = Aspose . Pdf . VerticalAlignment . None ,
IsFirstParagraphInColumn = false ,
IsKeptWithNext = false ,
IsInNewPage = false ,
IsInLineParagraph = false
});
document . Save ( dataDir + "AdjustTextPosition_out.pdf" );
}
Автоматическое создание тегированного PDF с преобразованием PDF/UA-1
Aspose.PDF позволяет автоматически генерировать базовую разметку логической структуры при преобразовании документа в PDF/UA-1. Пользователи могут затем вручную улучшить эту базовую логическую структуру, предоставляя дополнительные сведения о содержимом документа.
Чтобы сгенерировать логическую структуру документа, создайте экземпляр класса Aspose.Pdf.AutoTaggingSettings , установите свойство AutoTaggingSettings.EnableAutoTagging в true
и назначьте его свойству PdfFormatConversionOptions.AutoTaggingSettings .
Если документ уже имеет теги логической структуры, включение автоматического тегирования уничтожит существующую логическую структуру и создаст новую.