### Create PDF/UA Document Structure Elements Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Illustrates the process of building a document structure using BeginElement and End calls with the StructureBuilder. This example specifically creates a Heading1 and a Paragraph. ```C# sb.BeginElement(PdfBlockLevelElementTag.Heading1); gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); sb.End(); sb.BeginElement(PdfBlockLevelElementTag.Paragraph); // A trailing blank is needed here to make word break identification possible for screen readers. // If there are several DrawStrings in one BlockLevelElement, insert trailing blanks as if you would write the content as pure text. gfx.DrawString("Line 1 ", font, XBrushes.DarkBlue, 50, 200); gfx.DrawString("Line 2", font, XBrushes.DarkBlue, 50, 250); sb.End(); ``` -------------------------------- ### Create a Basic Document with MigraDoc Source: https://context7.com/empira/pdfsharp.samples/llms.txt Build a structured document using MigraDoc's object model, including sections, paragraphs, formatted text, and footers with date fields. This example demonstrates setting default styles and adding basic content. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Fields; using MigraDoc.Rendering; using PdfSharp.Pdf; // Create a new MigraDoc document var document = new Document(); // Set the default style font var style = document.Styles[StyleNames.Normal]!; style.Font.Name = "Arial"; // Add a section to the document var section = document.AddSection(); // Add a paragraph with formatted text var paragraph = section.AddParagraph(); paragraph.Format.Font.Color = Colors.DarkBlue; paragraph.AddFormattedText("Hello, World!", TextFormat.Bold); // Create the primary footer var footer = section.Footers.Primary; paragraph = footer.AddParagraph(); paragraph.Add(new DateField { Format = "yyyy/MM/dd HH:mm:ss" }); paragraph.Format.Alignment = ParagraphAlignment.Center; // Add an image document.LastSection.AddImage("logo.png"); // Create a renderer for the MigraDoc document var pdfRenderer = new PdfDocumentRenderer { Document = document, PdfDocument = { PageLayout = PdfPageLayout.SinglePage, ViewerPreferences = { FitWindow = true } } }; // Layout and render document to PDF pdfRenderer.RenderDocument(); // Save the document pdfRenderer.PdfDocument.Save("HelloMigraDoc.pdf"); ``` -------------------------------- ### Create Tables with MigraDoc Source: https://context7.com/empira/pdfsharp.samples/llms.txt Generate complex tables with MigraDoc, including cell formatting, borders, shading, and cell merging. This example shows how to define columns, add rows with header styling, and demonstrate merging cells horizontally and vertically. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.Rendering; using PdfSharp.Pdf; var document = new Document(); // Set Normal style var style = document.Styles[StyleNames.Normal]; style.ParagraphFormat.SpaceBefore = Unit.FromPoint(3); style.ParagraphFormat.SpaceAfter = Unit.FromPoint(3); var section = document.AddSection(); // Add table var table = section.AddTable(); table.Borders.Visible = true; // Add columns var columnA = table.AddColumn(Unit.FromCentimeter(2)); var columnB = table.AddColumn(Unit.FromCentimeter(3)); // Add first row with header styling var row1 = table.AddRow(); row1.Shading.Color = Colors.PaleGoldenrod; row1.HeadingFormat = true; row1.Cells[0].AddParagraph("Itemus"); row1.Cells[1].AddParagraph("Descriptum"); // Add data rows var row2 = table.AddRow(); row2.Cells[0].AddParagraph("1"); row2.Cells[1].AddParagraph("First item description"); var row3 = table.AddRow(); row3.Cells[0].AddParagraph("2"); row3.Cells[1].AddParagraph("Second item description"); // Set table edge border table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 1.5, Colors.Black); // Demonstrate cell merging var mergeTable = section.AddTable(); mergeTable.Borders.Visible = true; mergeTable.TopPadding = 5; mergeTable.BottomPadding = 5; mergeTable.AddColumn(); mergeTable.AddColumn(); mergeTable.AddColumn(); mergeTable.Rows.Height = 35; var mergeRow = mergeTable.AddRow(); mergeRow.Cells[0].AddParagraph("Merge Right"); mergeRow.Cells[0].MergeRight = 1; // Merge with next cell mergeRow = mergeTable.AddRow(); mergeRow.Cells[0].MergeDown = 1; // Merge with cell below mergeRow.Cells[0].VerticalAlignment = VerticalAlignment.Bottom; mergeRow.Cells[0].AddParagraph("Merge Down"); mergeTable.AddRow(); // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("TablesDemo.pdf"); ``` -------------------------------- ### Get StructureBuilder for PDF/UA Document Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Retrieve the StructureBuilder from the UAManager to define the document's structure. This is essential for organizing content semantically in PDF/UA documents. ```C# var sb = uaManager.StructureBuilder; // Get structure builder. ``` -------------------------------- ### PDF Structure Building with Using Statements Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV3/!ReadMe.md This sample demonstrates building PDF document structure using the 'using' statement, which offers a more concise and readable alternative to explicit BeginElement/End calls. ```C# // Paragraph sample. using (abc.UseElement(PdfGroupingElementTag.Article)) { var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); using (abc.UseElement(PdfBlockLevelElementTag.Heading1)) { gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); } using (abc.UseElement(PdfBlockLevelElementTag.Heading1)) { gfx.DrawString("Line 1", font, XBrushes.DarkBlue, 50, 200); gfx.DrawString("Line 2", font, XBrushes.DarkBlue, 50, 250); } } ``` -------------------------------- ### PDF Structure Building with BeginElement/End Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV3/!ReadMe.md This sample demonstrates building PDF document structure using explicit BeginElement and End calls. It's a more verbose method compared to using statements. ```C# // Paragraph sample. sb.BeginElement(PdfGroupingElementTag.Article); { var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); sb.BeginElement(PdfBlockLevelElementTag.Heading1); gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); sb.End(); sb.BeginElement(PdfBlockLevelElementTag.P); gfx.DrawString("Line 1", font, XBrushes.DarkBlue, 50, 200); gfx.DrawString("Line 2", font, XBrushes.DarkBlue, 50, 250); sb.End(); } sb.End(); ``` -------------------------------- ### Create Signed PDF Document with PDFsharp Source: https://context7.com/empira/pdfsharp.samples/llms.txt This C# code snippet demonstrates how to create a PDF document, add content, and apply a digital signature. It supports optional timestamping from a server. Ensure you have a valid 'certificate.pfx' file and the correct password. ```csharp using System.Security.Cryptography.X509Certificates; using PdfSharp.Drawing; using PdfSharp.Drawing.Layout; using PdfSharp.Pdf; using PdfSharp.Pdf.Signatures; // Create a signed document async Task CreateSignedDocument(bool addTimestamp = false) { var font = new XFont("Verdana", 10, XFontStyleEx.Regular); var fontHeader = new XFont("Verdana", 18, XFontStyleEx.Regular); using var document = new PdfDocument(); var pdfPage = document.AddPage(); var xGraphics = XGraphics.FromPdfPage(pdfPage); // Draw header var layoutRectangle = new XRect(0, 72, pdfPage.Width.Point, pdfPage.Height.Point); xGraphics.DrawString("License Agreement", fontHeader, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter); // Draw content using text formatter var textFormatter = new XTextFormatter(xGraphics); layoutRectangle = new XRect(72, 144, pdfPage.Width.Point - 144, pdfPage.Height.Point - 144); var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit..."; textFormatter.DrawString(text, font, XBrushes.Black, layoutRectangle, XStringFormats.TopLeft); // Configure digital signature options var pdfPosition = xGraphics.Transformer.WorldToDefaultPage(new XPoint(144, 600)); var options = new DigitalSignatureOptions { ContactInfo = "John Doe", Location = "Seattle", Reason = "License Agreement", Rectangle = new XRect(pdfPosition.X, pdfPosition.Y, 200, 50), AppearanceHandler = new SignatureAppearanceHandler() }; // Load certificate from .pfx file var certificate = new X509Certificate2("certificate.pfx", "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); // Create signature handler with optional timestamp Uri? timestampUri = addTimestamp ? new Uri("http://timestamp.apple.com/ts01") : null; var pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document, new PdfSharpDefaultSigner(certificate, PdfMessageDigestType.SHA256, timestampUri), options); // Save the signed document asynchronously await document.SaveAsync("SignedDocument.pdf"); } ``` -------------------------------- ### Create a Basic PDF Document with PDFsharp Source: https://context7.com/empira/pdfsharp.samples/llms.txt Use XGraphics to draw text, lines, and shapes directly onto PDF pages. Requires PdfSharp.Drawing and PdfSharp.Pdf namespaces. ```csharp using PdfSharp.Drawing; using PdfSharp.Fonts; using PdfSharp.Pdf; // Create a new PDF document var document = new PdfDocument(); document.Info.Title = "Created with PDFsharp"; document.Info.Subject = "Just a simple Hello-World program."; // Create an empty page in this document var page = document.AddPage(); // Get an XGraphics object for drawing on this page var gfx = XGraphics.FromPdfPage(page); // Draw two lines with a red default pen var width = page.Width.Point; var height = page.Height.Point; gfx.DrawLine(XPens.Red, 0, 0, width, height); gfx.DrawLine(XPens.Red, width, 0, 0, height); // Draw a circle with a red pen which is 1.5 point thick var r = width / 5; gfx.DrawEllipse(new XPen(XColors.Red, 1.5), XBrushes.White, new XRect(width / 2 - r, height / 2 - r, 2 * r, 2 * r)); // Create a font var font = new XFont("Times New Roman", 20, XFontStyleEx.BoldItalic); // Draw the text centered on the page gfx.DrawString("Hello, PDFsharp!", font, XBrushes.Black, new XRect(0, 0, page.Width.Point, page.Height.Point), XStringFormats.Center); // Save the document document.Save("HelloWorld.pdf"); ``` -------------------------------- ### Create and Render a Column and Line Chart Source: https://context7.com/empira/pdfsharp.samples/llms.txt Demonstrates how to create a MigraDoc document, add a section, and insert a chart with multiple series (column and line). It configures chart axes, plot area, and renders the document to a PDF file. Ensure MigraDoc libraries are referenced. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.Shapes.Charts; using MigraDoc.Rendering; var document = new Document(); var section = document.AddSection(); section.AddParagraph("Chart Overview", StyleNames.Heading1); section.AddParagraph("Sample Chart", StyleNames.Heading2); // Create a chart var chart = new Chart(); chart.Left = 0; chart.Width = Unit.FromCentimeter(16); chart.Height = Unit.FromCentimeter(12); // Add a column series with data labels var series = chart.SeriesCollection.AddSeries(); series.ChartType = ChartType.Column2D; series.Add(1, 17, 45, 5, 3, 20, 11, 23, 8, 19); series.HasDataLabel = true; // Add a line series series = chart.SeriesCollection.AddSeries(); series.ChartType = ChartType.Line; series.Add(41, 7, 5, 45, 13, 10, 21, 13, 18, 9); // Add X-axis labels var xSeries = chart.XValues.AddXSeries(); xSeries.Add("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N"); // Configure axes chart.XAxis.Title.Caption = "X-Axis"; chart.YAxis.MajorTickMark = TickMarkType.Outside; chart.YAxis.HasMajorGridlines = true; // Configure plot area chart.PlotArea.LineFormat.Color = Colors.DarkGray; chart.PlotArea.LineFormat.Width = 1; document.LastSection.Add(chart); // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("ChartsDemo.pdf"); ``` -------------------------------- ### Create PDF/UA Article with Heading and Paragraph Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Demonstrates creating a PDF/UA document with a basic structure including an article, a heading, and a paragraph. Ensure trailing blanks in DrawString calls within a BlockLevelElement for proper word break identification by screen readers. ```C# sb.BeginElement(PdfGroupingElementTag.Article); { var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); sb.BeginElement(PdfBlockLevelElementTag.Heading1); gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); sb.End(); sb.BeginElement(PdfBlockLevelElementTag.Paragraph); gfx.DrawString("Line 1", font, XBrushes.DarkBlue, 50, 200); gfx.DrawString("Line 2", font, XBrushes.DarkBlue, 50, 250); sb.End(); } sb.End(); ``` -------------------------------- ### Configure Headers and Footers in MigraDoc Source: https://context7.com/empira/pdfsharp.samples/llms.txt Set up section-specific headers and footers in MigraDoc, including options for odd/even pages, first page differentiation, and automatic page numbering. Tab stops can be used for footer alignment. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; var document = new Document(); // Style for header var style = document.Styles[StyleNames.Header]; style.ParagraphFormat.Alignment = ParagraphAlignment.Center; // Style for footer with tab stops style = document.Styles[StyleNames.Footer]; style.ParagraphFormat.ClearAll(); style.ParagraphFormat.TabStops.AddTabStop(Unit.FromCentimeter(8), TabAlignment.Center); style.ParagraphFormat.TabStops.AddTabStop(Unit.FromCentimeter(16), TabAlignment.Right); // First section var section = document.AddSection(); // Set up header var header = section.Headers.Primary; header.AddParagraph("Test document"); // Set up footer with page number var footer = section.Footers.Primary; var paragraph = footer.AddParagraph("\tSection one\t"); paragraph.AddPageField(); // Adds current page number // Add section content section.AddParagraph("Content of first section first page"); section.AddPageBreak(); section.AddParagraph("Content of first section second page"); // Second section - headers/footers inherited from previous section section = document.AddSection(); // Override footer with empty one (no footer in this section) section.Footers.Primary = new HeaderFooter(); section.AddParagraph("Content of second section (no footer)"); // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("HeadersFootersDemo.pdf"); ``` -------------------------------- ### Initialize UAManager for PDF/UA Document Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md This code must be called before any other operation on the document to make it PDF/UA compliant. It initializes the UAManager and prepares the document for structure definition. ```C# var uaManager = UAManager.ForDocument(document); ``` -------------------------------- ### Create a Simple Numbered List in PDF/UA Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Construct a numbered list using List and ListItem StructureElements. Each ListItem contains a Label and a ListBody for its content. ```C# // Create a new list. sb.BeginElement(PdfBlockLevelElementTag.List); { // Create the first list item. sb.BeginElement(PdfBlockLevelElementTag.ListItem); { // Create the label of the first list item. sb.BeginElement(PdfBlockLevelElementTag.Label); { gfx.DrawString("1)", font, XBrushes.DarkBlue, 50, 80); } sb.End(); // Add the list item's content into a ListBody structure element. sb.BeginElement(PdfBlockLevelElementTag.ListBody); { gfx.DrawString("Item 1", font, XBrushes.DarkBlue, 70, 80); } sb.End(); } sb.End(); // Create the second list item. ... } sb.End(); ``` -------------------------------- ### Create Document Link in C# Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Create links in PDF/UA documents by using `PdfLinkAnnotation.CreateDocumentLink` and `sb.BeginElement` with the annotation and alternative text. Ensure the bounding rectangle and target page are correctly specified. ```C# // Create a paragraph. sb.BeginElement(PdfBlockLevelElementTag.Paragraph); { // Create the links bounding rect. var rect = new PdfRectangle(gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(50, 90), new XPoint(205, 105)))); // Create a LinkAnnotation referring to page 2. var link = PdfLinkAnnotation.CreateDocumentLink(rect, 2); // Create a new Link structure element with the LinkAnnotation and the alternative text passed as parameters. sb.BeginElement(link, "Link to page 2"); { // Insert the text shown as link. gfx.DrawString("This is a link to the next page.", font, XBrushes.DarkBlue, 50, 100); } sb.End(); } sb.End(); ``` -------------------------------- ### Draw Link with Extension Method Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Create a Link StructureElement and draw the associated text in one line using the DrawLink extension method. ```C# gfx.DrawLink(string s, XFont font, XBrush brush, double x, double y, PdfLinkAnnotation linkAnnotation, string altText); ``` -------------------------------- ### Create Multi-level Lists in MigraDoc Source: https://context7.com/empira/pdfsharp.samples/llms.txt Define styles for different list levels (e.g., level 1 and level 2) with specific numbering formats and indentation. Apply these styles to paragraphs to construct multi-level lists. Ensure to set 'ContinuePreviousList' to false for the first item of a new list. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering.IO; var document = new Document(); // Style for list level 1 const string listLevel1StyleName = "ListLevel1"; var style = document.Styles.AddStyle(listLevel1StyleName, StyleNames.List); style.ParagraphFormat.ListInfo.ListType = ListType.NumberList1; // 1. 2. 3. style.ParagraphFormat.ListInfo.NumberPosition = Unit.Zero; style.ParagraphFormat.LeftIndent = Unit.FromCentimeter(0.5); // Style for list level 1, first item (starts new list) const string listLevel1Line1StyleName = "ListLevel1Line1"; style = document.Styles.AddStyle(listLevel1Line1StyleName, listLevel1StyleName); style.ParagraphFormat.ListInfo.ContinuePreviousList = false; // Style for list level 2 const string listLevel2StyleName = "ListLevel2"; style = document.Styles.AddStyle(listLevel2StyleName, StyleNames.List); style.ParagraphFormat.ListInfo.ListType = ListType.NumberList2; // a) b) c) style.ParagraphFormat.ListInfo.NumberPosition = Unit.FromCentimeter(0.5); style.ParagraphFormat.LeftIndent = Unit.FromCentimeter(1); // Style for list level 2, first item const string listLevel2Line1StyleName = "ListLevel2Line1"; style = document.Styles.AddStyle(listLevel2Line1StyleName, listLevel2StyleName); style.ParagraphFormat.ListInfo.ContinuePreviousList = false; var section = document.AddSection(); // First level 1 item (starts new list) var paragraph = section.AddParagraph("First main item"); paragraph.Style = listLevel1Line1StyleName; // Second level 1 item (continues list) paragraph = section.AddParagraph("Second main item"); paragraph.Style = listLevel1StyleName; // Level 2 item under second main item paragraph = section.AddParagraph("Sub-item under second main item"); paragraph.Style = listLevel2Line1StyleName; // Third level 1 item paragraph = section.AddParagraph("Third main item"); paragraph.Style = listLevel1StyleName; // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("ListsDemo.pdf"); ``` -------------------------------- ### Create PDF/UA Accessible Document with PDFsharp Source: https://context7.com/empira/pdfsharp.samples/llms.txt This C# code snippet shows how to create a PDF/UA compliant document using PDFsharp. It utilizes the UAManager to add structure tags for improved accessibility with screen readers. Ensure proper element nesting for correct structure. ```csharp using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.UniversalAccessibility; // Create PDF document var document = new PdfDocument(); document.ViewerPreferences.FitWindow = true; document.PageLayout = PdfPageLayout.SinglePage; // Get the manager for universal accessibility var uaManager = UAManager.ForDocument(document); // Create fonts var font = new XFont("Arial", 16, XFontStyleEx.Italic); var fontH1 = new XFont("Arial", 20, XFontStyleEx.Italic); // Get structure builder var sb = uaManager.StructureBuilder; // Create article element in document sb.BeginElement(PdfGroupingElementTag.Article); { // Create a page and graphics object var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); // Create Heading 1 element sb.BeginElement(PdfBlockLevelElementTag.Heading1); gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); sb.End(); // Create paragraph element sb.BeginElement(PdfBlockLevelElementTag.Paragraph); // Trailing blank needed for word break identification by screen readers gfx.DrawString("Line 1 ", font, XBrushes.DarkBlue, 50, 200); gfx.DrawString("Line 2", font, XBrushes.DarkBlue, 50, 250); sb.End(); } sb.End(); document.Save("AccessibleDocument.pdf"); ``` -------------------------------- ### Draw Image with Extension Method (various overloads) Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Use DrawImage extension methods to create Image StructureElements and images efficiently. If no bounding box is provided, it's determined from the image's position and size. ```C# gfx.DrawImage(XImage image, double x, double y, string altText, XRect boundingBox); ``` ```C# gfx.DrawImage(XImage image, double x, double y, double width, double height, string altText, XRect boundingBox); ``` ```C# gfx.DrawImage(XImage image, double x, double y, string altText); ``` ```C# gfx.DrawImage(XImage image, double x, double y, double width, double height, string altText); ``` -------------------------------- ### Draw String with Extension Method Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Utilize the extension method for a more readable way to draw strings with element tags. ```C# gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100, PdfBlockLevelElementTag.Heading1); ``` -------------------------------- ### Add Artifact Content in C# Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Use `sb.BeginArtifact()` and `sb.End()` to enclose content that should be ignored by screen readers and not considered part of the document's structure. This is useful for layout elements. ```C# // Insert an artifact. sb.BeginArtifact(); { // This text is, as it is included in the artifact, not handled as actual content of the document. A screen reader will skip this text. gfx.DrawString("An artifact", font, XBrushes.Gray, 50, 150); } sb.End(); ``` -------------------------------- ### Define and Apply Custom Styles Source: https://context7.com/empira/pdfsharp.samples/llms.txt Shows how to modify predefined styles (like Normal, Heading1) and create new custom styles (CodeBlock, TextBox, TOC) in MigraDoc. Custom styles can define font properties, paragraph formatting, borders, shading, and tab stops. These styles are then applied to document elements. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; var document = new Document(); // Modify the predefined Normal style - affects the whole document var style = document.Styles[StyleNames.Normal]!; style.Font.Name = "Arial"; // Customize Heading1 style style = document.Styles[StyleNames.Heading1]!; style.Font.Name = "Times New Roman"; style.Font.Size = 16; style.Font.Color = Colors.DarkBlue; style.ParagraphFormat.PageBreakBefore = true; style.ParagraphFormat.SpaceAfter = 6; style.ParagraphFormat.KeepWithNext = true; // Create a custom code block style const string codeBlockStyleName = "CodeBlock"; style = document.Styles.AddStyle(codeBlockStyleName, StyleNames.Normal); style.Font.Name = "Courier New"; style.ParagraphFormat.LeftIndent = Unit.FromCentimeter(1); style.ParagraphFormat.SpaceBefore = Unit.FromPoint(7); style.ParagraphFormat.SpaceAfter = Unit.FromPoint(7); // Create a custom TextBox style with borders and shading const string textBoxStyleName = "TextBox"; style = document.Styles.AddStyle(textBoxStyleName, StyleNames.Normal); style.ParagraphFormat.Alignment = ParagraphAlignment.Justify; style.ParagraphFormat.Borders.Width = 2.5; style.ParagraphFormat.Borders.Distance = "3pt"; style.ParagraphFormat.Shading.Color = Colors.SkyBlue; // Create a Table of Contents style with tab stops const string tocStyleName = "TOC"; style = document.Styles.AddStyle(tocStyleName, StyleNames.Normal); style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right, TabLeader.Dots); style.ParagraphFormat.Font.Color = Colors.Blue; // Use the styles var section = document.AddSection(); section.AddParagraph("How to setup an own style:"); var paragraph = section.AddParagraph("var style = document.Styles.AddStyle(styleName, StyleNames.Normal);\n" + "style.Font.Name = \"Courier New\";\n" + "style.ParagraphFormat.LeftIndent = Unit.FromCentimeter(1);"); paragraph.Style = codeBlockStyleName; // Apply custom style // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("StylesDemo.pdf"); ``` -------------------------------- ### Insert Image with Unchanged Size in PDF/UA Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Use BeginElement with PdfIllustrationElementTag.Figure to define the bounding box and alternate text for an image. The image size is determined from the XImage object. ```C# // Insert an image with unchanged size. // Create the figure and pass its alternate text and its bounding box as a parameter. var image = XImage.FromFile("../../assets/Z3.jpg"); sb.BeginElement(PdfIllustrationElementTag.Figure, "A BMW Z3 driving through a sandstone desert.", new XRect(50, 300, image.PointWidth, image.PointHeight)); { // Add the image as usual. gfx.DrawImage(image, 50, 300); } sb.End(); ``` -------------------------------- ### Draw String with Begin/End Elements Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Use BeginElement and End for single draw string calls when not using extension methods. ```C# sb.BeginElement(PdfBlockLevelElementTag.Heading1); gfx.DrawString("Header Text", fontH1, XBrushes.DarkBlue, 50, 100); sb.End(); ``` -------------------------------- ### Add Abbreviation with Expanded Text in C# Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Use `sb.BeginElement(PdfInlineLevelElementTag.Span)` and `sb.SetExpandedText` to define abbreviations with their expanded forms for screen readers. Ensure trailing spaces are included in both the drawn text and expanded text if they exist in the original content. ```C# sb.BeginElement(PdfBlockLevelElementTag.P); { // Insert simple text. gfx.DrawString("A text with an ", font, XBrushes.DarkBlue, 50, 100); // Insert a Span for an abbreviation. sb.BeginElement(PdfInlineLevelElementTag.Span); { // Draw the abbreviation. gfx.DrawString("abbr.", font, XBrushes.DarkBlue, 50, 120); // Set the expanded text for the abbreviation. Note that we also need the trailing blank here, if there was one in pure text representation. sb.SetExpandedText("abbreviation "); } sb.End(); // Insert further text. gfx.DrawString("in a structure element in the middle.", font, XBrushes.DarkBlue, 50, 140); } sb.End(); ``` -------------------------------- ### Create Hyperlinks in MigraDoc Source: https://context7.com/empira/pdfsharp.samples/llms.txt Use MigraDoc to add hyperlinks to web URLs, local files, or email addresses within a document. Styles can be applied to hyperlinks for visual distinction. ```csharp using MigraDoc.DocumentObjectModel; using MigraDoc.Rendering; var document = new Document(); // Style for hyperlinks var style = document.Styles[StyleNames.Hyperlink]; style.Font.Color = Colors.Blue; style.Font.Underline = Underline.Single; var section = document.AddSection(); // Link to a web URL var paragraph = section.AddParagraph("Follow this "); var hyperlink = paragraph.AddHyperlink("https://docs.pdfsharp.net", HyperlinkType.Url); hyperlink.AddText("link"); paragraph.AddText(" to visit the documentation."); // Link using CreateWebLink helper (adds HTTP if protocol omitted) paragraph = section.AddParagraph("Or use this "); hyperlink = Hyperlink.CreateWebLink("docs.pdfsharp.net"); paragraph.Add(hyperlink); hyperlink.AddText("link"); paragraph.AddText(" without specifying the protocol."); // Render to PDF var pdfRenderer = new PdfDocumentRenderer { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save("HyperlinksDemo.pdf"); ``` -------------------------------- ### Draw Abbreviation with Extension Method Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Create a span with an abbreviation and its expanded text in a single line of code using the DrawAbbreviation extension method. ```C# gfx.DrawAbbreviation(string abbreviation, string expandedText, XFont font, XBrush brush, double x, double y); ``` -------------------------------- ### Customize Text Rendering with PDFsharp Render Events Source: https://context7.com/empira/pdfsharp.samples/llms.txt Register a render event handler to intercept and modify text rendering at the glyph level. This is useful for character substitution and handling missing glyphs. The handler modifies code points and re-evaluates glyph indices. ```csharp using PdfSharp.Drawing; using PdfSharp.Pdf; var document = new PdfDocument(); var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); // Register a render event handler document.RenderEvents.RenderTextEvent += (sender, args) => { for (int idx = 0; idx < args.CodePointGlyphIndexPairs.Length; idx++) { // Use a reference because CodePointWithGlyphIndex is a value type ref var item = ref args.CodePointGlyphIndexPairs[idx]; // Replace X with U if (item.CodePoint == 'X') { item.CodePoint = 'U'; args.ReevaluateGlyphIndices = true; } const char nonBreakHyphen = '\u2011'; // Replace non-break hyphen with '-' if font does not contain a glyph for it if (item.CodePoint == nonBreakHyphen && item.GlyphIndex == 0) { item.CodePoint = '-'; item.GlyphIndex = GlyphHelper.GlyphIndexFromCodePoint('-', args.Font); } } }; const string someText = "ABC\u2011XYZ"; var font = new XFont("Arial", 20, XFontStyleEx.Regular); // Text will be rendered as "ABC-UYZ" due to the event handler gfx.DrawString(someText, font, XBrushes.Black, 100, 100); document.Save("RenderEventsDemo.pdf"); ``` -------------------------------- ### Insert Image with Defined Size in PDF/UA Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Embed an image in a PDF/UA document with a specified size using BeginElement and DrawImage. The bounding box is defined by an XRect with explicit width and height. ```C# // Insert an image with a defined size. // Create the figure and pass its alternate text and its bounding box as a parameter. sb.BeginElement(PdfIllustrationElementTag.Figure, "A scaled BMW Z3 driving through a sandstone desert.", new XRect(50, 500, 400, 300)); { // Add the image as usual. gfx.DrawImage(XImage.FromFile("../../assets/Z3.jpg"), 50, 500, 400, 300); } sb.End(); ``` -------------------------------- ### AES-256 Encryption and Decryption with PDFsharp Source: https://context7.com/empira/pdfsharp.samples/llms.txt Encrypt PDF documents using AES 256-bit security with user and owner passwords. Supports PDF 2.0 encryption standards. Requires PdfSharp.Pdf.Security namespace. ```csharp using PdfSharp.Drawing; using PdfSharp.Pdf; using PdfSharp.Pdf.IO; using PdfSharp.Pdf.Security; const string userPassword = "User"; // Create a new PDF document var document = new PdfDocument(); document.Info.Title = "AES 256 bit encryption demonstration"; document.PageLayout = PdfPageLayout.SinglePage; // Create an empty page and draw content var page = document.AddPage(); var gfx = XGraphics.FromPdfPage(page); var font = new XFont("Times New Roman", 20, XFontStyleEx.BoldItalic); gfx.DrawString("AES 256 bit test", font, XBrushes.Black, new XRect(0, 0, page.Width.Point, page.Height.Point), XStringFormats.Center); // Set document encryption document.SecuritySettings.UserPassword = userPassword; var securityHandler = document.SecurityHandler; securityHandler.SetEncryptionToV5(); // Save the encrypted document document.Save("EncryptedDocument.pdf"); // Open the encrypted PDF document with password var openedDocument = PdfReader.Open("EncryptedDocument.pdf", userPassword, PdfDocumentOpenMode.Modify); // Add a second page to the opened document var page2 = openedDocument.AddPage(); var gfx2 = XGraphics.FromPdfPage(page2); gfx2.DrawString("2nd page", font, XBrushes.Black, new XRect(0, 0, page2.Width.Point, page2.Height.Point), XStringFormats.Center); // Save without encryption (password removed after opening) openedDocument.Save("DecryptedDocument.pdf"); ``` -------------------------------- ### Draw List Item with Extension Method Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/FeaturesV2/!ReadMe.md Generate a ListItem StructureElement with its children (Label and ListBody) in a single call using the DrawListItem extension method. ```C# gfx.DrawListItem(string label, string text, XFont font, XBrush brush, double x, double y, double labelWidth); ``` -------------------------------- ### Set Document Language in C# Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Set the default language for the entire PDF/UA document using `uaManager.SetDocumentLanguage`. This helps screen readers pronounce text correctly. ```C# uaManager.SetDocumentLanguage("en-US"); ``` -------------------------------- ### Create Custom Bullet for List Item Label in PDF/UA Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Use drawing methods like DrawEllipse within a Label StructureElement to create custom bullets for list items. Ensure accessibility by setting alternate text with SetAltText. ```C# // Create the label of the first list item. sb.BeginElement(PdfBlockLevelElementTag.Label); { // Draw an ellipse as the list item's label. gfx.DrawEllipse(XBrushes.DarkBlue, 50, 75, 3, 3); // Set the alternative text for the label's structure element. sb.SetAltText("Bullet"); } sb.End(); ``` -------------------------------- ### Add List Body Content with Nested List in PDF/UA Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Define the content for a list item, including a nested list, by creating a ListBody StructureElement. This allows for hierarchical list structures. ```C# // Create a LBody structure element for the second list item. sb.BeginElement(PdfBlockLevelElementTag.ListBody); { // Draw some text. gfx.DrawString("Item 2", font, XBrushes.DarkBlue, 70, 100); // Create a nested list. sb.BeginElement(PdfBlockLevelElementTag.List); { ... } sb.End(); } sb.End(); ``` -------------------------------- ### Create Paragraph Spanning Multiple Pages Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Shows how to create a single paragraph that extends across multiple pages in a PDF/UA document. Page breaks are managed by adding new pages and continuing the DrawString operations within the same paragraph element. ```C# sb.BeginElement(PdfBlockLevelElementTag.Paragraph); { // Draw text on first page. gfx.DrawString("A paragraph that contains text content on its first page, ", font, XBrushes.DarkBlue, 50, 100); // Break to second page. page = document.AddPage(); gfx = XGraphics.FromPdfPage(page); // Draw text on second page, but still same paragraph. gfx.DrawString("text content, ", font, XBrushes.DarkBlue, 50, 100); ... } sb.End(); ``` -------------------------------- ### Change Span Language in C# Source: https://github.com/empira/pdfsharp.samples/blob/master/src/samples/src/PDFsharp/src/Pdf.Accessibility/UAFeatures/Features/!ReadMe.md Change the language for a specific structure element, such as a `Span`, using `sb.SetLanguage`. This overrides the document's default language for that element. ```C# sb.BeginElement(PdfInlineLevelElementTag.Span); { // Change the language for the current structure element. sb.SetLanguage("de-DE"); // Insert the text in the new language. gfx.DrawString("\"Herzlichen Glückwunsch!\" ", font, XBrushes.DarkBlue, 50, 200); } sb.End(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.