Создание помеченного 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.
Проверки для действий.
Проверки для необязательного контента.
Проверки для встроенных файлов.
Проверки для полей Acroform (Проверка естественного языка и альтернативного имени и цифровых подписей).
Проверки для полей формы XFA.
Проверки для настроек безопасности.
Проверки для навигации.
Проверки для аннотаций.
Ниже приведен фрагмент кода, который показывает, как проверить помеченный PDF-документ. Соответствующие проблемы будут отображены в XML-отчете.
Настройка позиции структуры текста
Следующий фрагмент кода показывает, как настроить позицию структуры текста в документе Tagged 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" );
}