### Creating a Basic PDF Document
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
This example demonstrates how to initialize a PDF document, add a page, draw text using XGraphics, and save the resulting file.
```APIDOC
## Create PDF Document
### Description
Initializes a new PDF document instance, adds a page, and renders text content using the PdfSharpCore drawing API.
### Method
N/A (Library Class Method)
### Endpoint
N/A
### Parameters
#### Request Body
- **Title** (string) - Optional - Document metadata title
- **Author** (string) - Optional - Document metadata author
### Request Example
```csharp
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharpCore";
```
### Response
#### Success Response (200)
- **File** (binary) - Returns a generated .pdf file saved to the specified path.
```
--------------------------------
### Example Custom Font Resolver Implementation
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/FontResolver.md
A complete example class implementing IFontResolver. It demonstrates how to map font families to specific TTF files and load them from the file system.
```csharp
using System;
using System.IO;
using PdfSharpCore.Utils;
public class MyFontResolver : IFontResolver
{
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
if (familyName.Equals("OpenSans", StringComparison.CurrentCultureIgnoreCase))
{
if (isBold && isItalic) return new FontResolverInfo("OpenSans-BoldItalic.ttf");
else if (isBold) return new FontResolverInfo("OpenSans-Bold.ttf");
else if (isItalic) return new FontResolverInfo("OpenSans-Italic.ttf");
else return new FontResolverInfo("OpenSans-Regular.ttf");
}
return null;
}
public byte[] GetFont(string faceName)
{
var faceNamePath = Path.Join("my path", faceName);
using(var ms = new MemoryStream())
{
using(var fs = File.OpenRead(faceNamePath))
{
fs.CopyTo(ms);
ms.Position = 0;
return ms.ToArray();
}
}
}
}
```
--------------------------------
### Configure Headers, Footers, and Page Setup with MigraDocCore
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
This C# code snippet illustrates how to configure headers, footers, and page numbering for a PDF document using MigraDocCore. It shows setting up styles for headers and footers, defining page setup properties like starting page number and odd/even page headers/footers, and adding content with page breaks. The final document is rendered and saved using PDFSharpCore.
```csharp
using MigraDocCore.DocumentObjectModel;
using MigraDocCore.Rendering;
using PdfSharpCore.Pdf;
Document document = new Document();
// Configure styles for header and footer
Style style = document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Add section with page setup
Section section = document.AddSection();
section.PageSetup.OddAndEvenPagesHeaderFooter = true;
section.PageSetup.StartingNumber = 1;
// Configure odd page header
HeaderFooter header = section.Headers.Primary;
header.AddParagraph("\tOdd Page Header");
// Configure even page header
header = section.Headers.EvenPage;
header.AddParagraph("Even Page Header");
// Create footer with page number
Paragraph footerPara = new Paragraph();
footerPara.AddTab();
footerPara.AddPageField();
// Add to both odd and even footers (clone required)
section.Footers.Primary.Add(footerPara);
section.Footers.EvenPage.Add(footerPara.Clone());
// Add content
for (int i = 1; i <= 5; i++)
{
section.AddParagraph($"Page {i} Content", "Heading1");
section.AddParagraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
if (i < 5) section.AddPageBreak();
}
// Render
PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();
renderer.PdfDocument.Save("MigraDocHeadersFooters.pdf");
```
--------------------------------
### Create a PDF document with text using PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/README.md
This example demonstrates how to initialize the global font resolver, create a new PDF document, add a page, and draw text onto it. It requires the PdfSharpCore NuGet package and is designed for .NET 6+ console applications.
```csharp
using PdfSharpCore.Drawing;
using PdfSharpCore.Fonts;
using PdfSharpCore.Pdf;
using PdfSharpCore.Utils;
GlobalFontSettings.FontResolver = new FontResolver();
var document = new PdfDocument();
var page = document.AddPage();
var gfx = XGraphics.FromPdfPage(page);
var font = new XFont("Arial", 20, XFontStyle.Bold);
var textColor = XBrushes.Black;
var layout = new XRect(20, 20, page.Width, page.Height);
var format = XStringFormats.Center;
gfx.DrawString("Hello World!", font, textColor, layout, format);
document.Save("helloworld.pdf");
```
--------------------------------
### Text Styling and Alignment
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Shows various text formatting options including fonts, styles, colors, and text alignment within rectangles. This example covers creating different font styles and demonstrating precise text placement.
```APIDOC
## Text Styling and Alignment
### Description
Shows various text formatting options including fonts, styles, colors, and text alignment within rectangles.
### Method
Not Applicable (Code Example)
### Endpoint
Not Applicable (Code Example)
### Parameters
Not Applicable (Code Example)
### Request Example
Not Applicable (Code Example)
### Response
#### Success Response (200)
Generates a PDF file named "TextStyling.pdf" demonstrating different text styles and alignments.
#### Response Example
```csharp
// See C# code example for details.
```
## Text Alignment within a Rectangle
### Description
Demonstrates how to align text (top, center, bottom, left, center, right) within a specified rectangular area.
### Method
Not Applicable (Code Example)
### Endpoint
Not Applicable (Code Example)
### Parameters
Not Applicable (Code Example)
### Request Example
Not Applicable (Code Example)
### Response
#### Success Response (200)
The "TextStyling.pdf" file will contain text elements precisely aligned within a rectangle.
#### Response Example
```csharp
// See C# code example for details.
```
```
--------------------------------
### Define Tables in PDFsharp Core
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Demonstrates how to create tables in a PDF document. Includes examples for simple table creation, cell alignment, and merging cells. This function relies on the PDFsharp library and takes a Document object as input.
```csharp
public static void DefineTables(Document document)
{
Paragraph paragraph = document.LastSection.AddParagraph("Table Overview", "Heading1");
paragraph.AddBookmark("Tables");
DemonstrateSimpleTable(document);
DemonstrateAlignment(document);
DemonstrateCellMerge(document);
}
public static void DemonstrateSimpleTable(Document document)
{
document.LastSection.AddParagraph("Simple Tables", "Heading2");
Table table = new Table();
table.Borders.Width = 0.75;
Column column = table.AddColumn(Unit.FromCentimeter(2));
column.Format.Alignment = ParagraphAlignment.Center;
table.AddColumn(Unit.FromCentimeter(5));
Row row = table.AddRow();
row.Shading.Color = Colors.PaleGoldenrod;
Cell cell = row.Cells[0];
cell.AddParagraph("Itemus");
cell = row.Cells[1];
cell.AddParagraph("Descriptum");
row = table.AddRow();
cell = row.Cells[0];
cell.AddParagraph("1");
cell = row.Cells[1];
cell.AddParagraph(FillerText.ShortText);
row = table.AddRow();
cell = row.Cells[0];
cell.AddParagraph("2");
cell = row.Cells[1];
cell.AddParagraph(FillerText.Text);
table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 1.5, Colors.Black);
document.LastSection.Add(table);
}
public static void DemonstrateAlignment(Document document)
{
document.LastSection.AddParagraph("Cell Alignment", "Heading2");
Table table = document.LastSection.AddTable();
table.Borders.Visible = true;
table.Format.Shading.Color = Colors.LavenderBlush;
table.Shading.Color = Colors.Salmon;
table.TopPadding = 5;
table.BottomPadding = 5;
Column column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Center;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Right;
table.Rows.Height = 35;
Row row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Top;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Center;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].AddParagraph("Text");
row.Cells[1].AddParagraph("Text");
row.Cells[2].AddParagraph("Text");
}
public static void DemonstrateCellMerge(Document document)
{
document.LastSection.AddParagraph("Cell Merge", "Heading2");
Table table = document.LastSection.AddTable();
table.Borders.Visible = true;
table.TopPadding = 5;
table.BottomPadding = 5;
Column column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Center;
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Right;
table.Rows.Height = 35;
Row row = table.AddRow();
row.Cells[0].AddParagraph("Merge Right");
row.Cells[0].MergeRight = 1;
row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].MergeDown = 1;
row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].AddParagraph("Merge Down");
table.AddRow();
}
```
--------------------------------
### Draw Pies with PDFsharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Shows how to draw pie segments by defining a bounding box, start angle, and sweep angle. Useful for creating charts or circular sectors.
```csharp
void DrawPie(XGraphics gfx, int number)
{
BeginBox(gfx, number, "DrawPie");
XPen pen = new XPen(XColors.DarkBlue, 2.5);
gfx.DrawPie(pen, 10, 0, 100, 90, -120, 75);
gfx.DrawPie(XBrushes.Gold, 130, 0, 100, 90, -160, 150);
gfx.DrawPie(pen, XBrushes.Gold, 10, 50, 100, 90, 80, 70);
gfx.DrawPie(pen, XBrushes.Gold, 150, 80, 60, 60, 35, 290);
EndBox(gfx);
}
```
--------------------------------
### Concatenate and Number PDF Pages
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/ConcatenateDocuments.md
This example demonstrates how to open multiple PDF files, import their pages, add each page twice to an output document, and number each added page consecutively. It also shows how to set the page layout for facing pages.
```APIDOC
## Concatenate and Number PDF Pages
### Description
This endpoint demonstrates how to open multiple PDF files, import their pages, add each page twice to an output document, and number each added page consecutively. It also shows how to set the page layout for facing pages.
### Method
N/A (This is a code example, not an API endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```csharp
// Assuming 'files' is a string array containing paths to input PDF files
// and 'outputDocument' is an initialized PdfDocument object
XFont font = new XFont("Verdana", 40, XFontStyle.Bold);
int number = 0;
// Iterate files
foreach (string file in files)
{
// Open the document to import pages from it.
PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);
// Show consecutive pages facing. Requires Acrobat 5 or higher.
outputDocument.PageLayout = PdfPageLayout.TwoColumnLeft;
// Iterate pages
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
// Get the page from the external document...
PdfPage page = inputDocument.Pages[idx];
// ...and add it twice to the output document.
PdfPage page1 = outputDocument.AddPage(page);
PdfPage page2 = outputDocument.AddPage(page);
XGraphics gfx = XGraphics.FromPdfPage(page1, XGraphicsPdfPageOptions.Append);
DrawNumber(gfx, font, ++number);
gfx = XGraphics.FromPdfPage(page2, XGraphicsPdfPageOptions.Append);
DrawNumber(gfx, font, ++number);
}
}
// Save the document...
const string filename = "ConcatenatedDocument4_tempfile.pdf";
outputDocument.Save(filename);
// Helper function to draw the number (implementation not shown)
// void DrawNumber(XGraphics gfx, XFont font, int number) { ... }
```
### Response
N/A (This is a code example)
### Response Example
N/A
```
--------------------------------
### Initialize and Render MigraDocCore Document
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Demonstrates the main entry point for creating a MigraDocCore document, rendering it to a PDF format, and saving the resulting file to disk.
```csharp
static void Main()
{
Document document = Documents.CreateDocument();
MigraDocCore.DocumentObjectModel.IO.DdlWriter.WriteToFile(document, "MigraDocCore.mdddl");
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();
string filename = "HelloMigraDoc.pdf";
renderer.PdfDocument.Save(filename);
}
```
--------------------------------
### Add Transparent Path Watermark Above Text - C#
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Watermark.md
This example shows how to draw a watermark as a transparent graphical path positioned above the existing text content. It uses XGraphics with the 'Append' option and prepares an XGraphicsPath. Similar to the previous example, the AddString method is not available in PdfSharpCore Core.
```csharp
// Variation 3: Draw a watermark as a transparent graphical path above text.
// NYI: Does not work in Core build.
// Get an XGraphics object for drawing above the existing content.
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
// Get the size (in points) of the text.
var size = gfx.MeasureString(watermark, font);
// Define a rotation transformation at the center of the page.
gfx.TranslateTransform(page.Width / 2, page.Height / 2);
gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);
// Create a graphical path.
var path = new XGraphicsPath();
// Create a string format.
var format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
// Add the text to the path.
// AddString is not implemented in PdfSharpCore Core.
path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, 150,
new XPoint((page.Width - si
```
--------------------------------
### Initialize PDF Document and Graphics
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Demonstrates the main entry point for creating a new PDF document and initializing the drawing process for various graphical content pages.
```csharp
static void Main()
{
string filename = String.Format("{0}_tempfile.pdf", Guid.NewGuid().ToString("D").ToUpper());
s_document = new PdfDocument();
s_document.Info.Title = "PdfSharpCore XGraphic Sample";
s_document.Info.Author = "Stefan Lange";
s_document.Info.Subject = "Created with code snippets that show the use of graphical functions";
s_document.Info.Keywords = "PdfSharpCore, XGraphics";
new LinesAndCurves().DrawPage(s_document.AddPage());
new Shapes().DrawPage(s_document.AddPage());
new Paths().DrawPage(s_document.AddPage());
new Text().DrawPage(s_document.AddPage());
new Images().DrawPage(s_document.AddPage());
s_document.Save(filename);
}
```
--------------------------------
### Initialize and Render MigraDocCore PDF
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloWorld.md
The Main method demonstrates how to instantiate a PdfDocumentRenderer, associate a document, configure global PDF settings like Unicode encoding and font embedding, and finally save the output to a file.
```csharp
static void Main(string[] args)
{
Document document = CreateDocument();
document.UseCmykColor = true;
const bool unicode = false;
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
const string filename = "HelloWorld.pdf";
pdfRenderer.PdfDocument.Save(filename);
}
```
--------------------------------
### Draw Image in Original Size (C#)
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Shows how to draw an image onto a PDF page at its original size, calculating the correct position to center it horizontally. This example uses a JPEG image.
```csharp
void DrawImage(XGraphics gfx, int number)
{
BeginBox(gfx, number, "DrawImage (original)");
XImage image = XImage.FromFile(jpegSamplePath);
// Left position in point
double x = (250 - image.PixelWidth * 72 / image.HorizontalResolution) / 2;
gfx.DrawImage(image, x, 0);
EndBox(gfx);
}
```
--------------------------------
### Creating PDF Bookmarks and Outlines
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Demonstrates how to implement a navigation structure in a PDF by creating root and nested bookmarks linked to specific pages.
```csharp
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
PdfDocument document = new PdfDocument();
XFont font = new XFont("Verdana", 16);
// Create first page
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawString("Page 1", font, XBrushes.Black, 20, 50, XStringFormats.Default);
// Create the root bookmark with custom style and color
PdfOutline outline = document.Outlines.Add("Root", page, true, PdfOutlineStyle.Bold, XColors.Red);
// Create more pages with sub-bookmarks
for (int idx = 2; idx <= 5; idx++)
{
page = document.AddPage();
gfx = XGraphics.FromPdfPage(page);
string text = "Page " + idx;
gfx.DrawString(text, font, XBrushes.Black, 20, 50, XStringFormats.Default);
// Create a sub-bookmark under the root
outline.Outlines.Add(text, page, true);
}
document.Save("Bookmarks.pdf");
```
--------------------------------
### Applying Password Protection and Security
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Illustrates how to load an existing PDF, apply user and owner passwords, and configure specific document permissions such as printing and content extraction.
```csharp
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
using PdfSharpCore.Pdf.Security;
// Open an existing document
PdfDocument document = PdfReader.Open("input.pdf", PdfDocumentOpenMode.Modify);
PdfSecuritySettings securitySettings = document.SecuritySettings;
// Set passwords (automatically enables 128-bit encryption)
securitySettings.UserPassword = "user"; // Required to open
securitySettings.OwnerPassword = "owner"; // Required to change permissions
// Configure document permissions
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = false;
securitySettings.PermitModifyDocument = true;
securitySettings.PermitPrint = false;
document.Save("protected.pdf");
```
--------------------------------
### Create Basic PDF Document with PdfSharpCore
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Demonstrates the fundamental workflow of creating a PDF document from scratch using PdfSharpCore. It includes setting document information, adding a page, defining a font, and drawing centered text. This requires the PdfSharpCore library.
```csharp
using PdfSharpCore.Drawing;
using PdfSharpCore.Fonts;
using PdfSharpCore.Pdf;
using PdfSharpCore.Utils;
// Set up the font resolver (required for .NET Core)
GlobalFontSettings.FontResolver = new FontResolver();
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharpCore";
document.Info.Author = "Your Name";
document.Info.Subject = "Sample PDF Document";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text centered on the page
gfx.DrawString(
"Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document
document.Save("HelloWorld.pdf");
```
--------------------------------
### Generate PDF with Text using C# and PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/HelloWorld.md
This C# code snippet demonstrates how to create a simple PDF document with the text 'Hello, World!' centered on the page. It utilizes the PdfSharpCore library to manage PDF creation, drawing operations, and file saving. The code initializes a PDF document, adds a page, sets up a font, draws the text, and saves the output to a file named 'HelloWorld.pdf'.
```csharp
using System;
using System.Diagnostics;
using System.IO;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
namespace HelloWorld
{
///
/// This sample is the obligatory Hello World program.
///
class Program
{
static void Main(string[] args)
{
// Create a new PDF document
PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PdfSharpCore";
// Create an empty page
PdfPage page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
// Create a font
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
// Draw the text
gfx.DrawString(
"Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// Save the document...
const string filename = "HelloWorld.pdf";
document.Save(filename);
}
}
}
```
--------------------------------
### Construct Document Structure
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Shows how to instantiate a Document object and orchestrate the population of various sections including styles, cover pages, and content blocks.
```csharp
public static Document CreateDocument()
{
Document document = new Document();
document.Info.Title = "Hello, MigraDocCore";
document.Info.Subject = "Demonstrates an excerpt of the capabilities of MigraDocCore.";
document.Info.Author = "Stefan Lange";
Styles.DefineStyles(document);
Cover.DefineCover(document);
TableOfContents.DefineTableOfContents(document);
DefineContentSection(document);
Paragraphs.DefineParagraphs(document);
Tables.DefineTables(document);
Charts.DefineCharts(document);
return document;
}
```
--------------------------------
### Define Content Section in C#
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Defines page setup, headers, and footers for a new section in a PDF document using PDFSharp Core. It configures odd and even page headers and footers, and adds a centered page number to the footer. This function requires a 'Document' object as input and adds a new section to it.
```C#
///
/// Defines page setup, headers, and footers.
///
static void DefineContentSection(Document document)
{
Section section = document.AddSection();
section.PageSetup.OddAndEvenPagesHeaderFooter = true;
section.PageSetup.StartingNumber = 1;
HeaderFooter header = section.Headers.Primary;
header.AddParagraph("\tOdd Page Header");
header = section.Headers.EvenPage;
header.AddParagraph("Even Page Header");
// Create a paragraph with centered page number. See definition of style "Footer".
Paragraph paragraph = new Paragraph();
paragraph.AddTab();
paragraph.AddPageField();
// Add paragraph to footer for odd pages.
section.Footers.Primary.Add(paragraph);
// Add clone of paragraph to footer for odd pages. Cloning is necessary because an object must
// not belong to more than one other object. If you forget cloning an exception is thrown.
section.Footers.EvenPage.Add(paragraph.Clone());
}
```
--------------------------------
### Clip Content Using a Text Path
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
This example shows how to use a text string as a clipping region in PDFsharp. The AddString method creates an XGraphicsPath from the text 'Clip!', and then IntersectClip is called with this path. Subsequent drawing operations are confined within the boundaries of the text path. A loop draws dotted lines that are clipped by the text.
```csharp
void DrawClipPath(XGraphics gfx, int number)
{
BeginBox(gfx, number, "Clip through Path");
XGraphicsPath path = new XGraphicsPath();
path.AddString(
"Clip!", new XFontFamily("Verdana"),
XFontStyle.Bold, 90,
new XRect(0, 0, 250, 140),
XStringFormats.Center
);
gfx.IntersectClip(path);
// Draw a beam of dotted lines
XPen pen = XPens.DarkRed.Clone();
pen.DashStyle = XDashStyle.Dot;
for (double r = 0; r <= 90; r += 0.5)
{
gfx.DrawLine(
pen, 0, 0,
250 * Math.Cos(r / 90 * Math.PI),
250 * Math.Sin(r / 90 * Math.PI)
);
}
EndBox(gfx);
}
```
--------------------------------
### Create PDF Document
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/index.md
Demonstrates the basic workflow for initializing a PDF document, adding a page, and drawing text using XGraphics.
```APIDOC
## POST /document/create
### Description
Initializes a new PDF document and draws a 'Hello World' string onto the first page.
### Method
POST
### Endpoint
/document/create
### Parameters
#### Request Body
- **filename** (string) - Required - The name of the file to save the generated PDF.
### Request Example
{
"filename": "HelloWorld.pdf"
}
### Response
#### Success Response (200)
- **status** (string) - Confirmation that the PDF was saved successfully.
#### Response Example
{
"status": "success",
"path": "HelloWorld.pdf"
}
```
--------------------------------
### Create Opened and Styled Text Annotations
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Annotations.md
Shows how to create an annotation that is initialized in an open state with custom color and opacity settings.
```csharp
textAnnot = new PdfTextAnnotation();
textAnnot.Title = "Annotation 2 (title)";
textAnnot.Subject = "Annotation 2 (subject)";
textAnnot.Contents = "This is the contents of the 2nd annotation.";
textAnnot.Icon = PdfTextAnnotationIcon.Help;
textAnnot.Color = XColors.LimeGreen;
textAnnot.Opacity = 0.5;
textAnnot.Open = true;
gfx.DrawString("The second text annotation (opened)", font, XBrushes.Black, 30, 140, XStringFormats.Default);
rect = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 150), new XSize(30, 30)));
textAnnot.Rectangle = new PdfRectangle(rect);
page.Annotations.Add(textAnnot);
```
--------------------------------
### Initialize and Populate XForm Template
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/XForms.md
Demonstrates how to instantiate an XForm object and use XGraphics to draw text, shapes, images, and other forms onto the template. The XGraphics object must be disposed after drawing is complete to finalize the form.
```csharp
XForm form = new XForm(document, XUnit.FromMillimeter(70), XUnit.FromMillimeter(55));
XGraphics formGfx = XGraphics.FromForm(form);
XColor back = XColors.Orange;
back.A = 0.2;
XSolidBrush brush = new XSolidBrush(back);
formGfx.DrawRectangle(brush, -10000, -10000, 20000, 20000);
formGfx.DrawString("Text, Graphics, Images, and Forms", new XFont("Verdana", 10, XFontStyle.Regular), XBrushes.Navy, 3, 0, XStringFormats.TopLeft);
XPen pen = XPens.LightBlue.Clone();
pen.Width = 2.5;
formGfx.DrawBeziers(pen, XPoint.ParsePoints("30,120 80,20 100,140 175,33.3"));
XGraphicsState state = formGfx.Save();
formGfx.RotateAtTransform(17, new XPoint(30, 30));
formGfx.DrawImage(XImage.FromFile("../../../../../../dev/XGraphicsLab/images/Test.gif"), 20, 20);
formGfx.Restore(state);
state = formGfx.Save();
formGfx.RotateAtTransform(-8, new XPoint(165, 115));
formGfx.DrawImage(XPdfForm.FromFile("../../../../../PDFs/SomeLayout.pdf"), new XRect(140, 80, 50, 50 * Math.Sqrt(2)));
formGfx.Restore(state);
formGfx.Dispose();
```
--------------------------------
### BeginBox Method
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Initializes a drawing area with a rounded rectangle, shadow, gradient background, and title header.
```APIDOC
## BeginBox
### Description
Draws a styled box on the provided XGraphics context, including a shadow, a vertical gradient background, and a title. It also saves the current graphics state to allow for coordinate transformation.
### Method
N/A (C# Method)
### Parameters
- **gfx** (XGraphics) - Required - The graphics context to draw on.
- **number** (int) - Required - Used to calculate the position of the box on the page.
- **title** (string) - Required - The text to display at the top of the box.
### Response
- **void** - This method performs side effects on the provided XGraphics object.
```
--------------------------------
### Create Charts (Column, Line, Pie) with MigraDocCore
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Illustrates the creation of various chart types, including column and line charts, using MigraDocCore. The code shows how to configure chart elements, add data series, and set axis labels and titles.
```csharp
using MigraDocCore.DocumentObjectModel;
using MigraDocCore.DocumentObjectModel.Shapes.Charts;
using MigraDocCore.Rendering;
using PdfSharpCore.Pdf;
Document document = new Document();
Section section = document.AddSection();
section.AddParagraph("Sales Chart", "Heading1");
// Create chart
Chart chart = new Chart();
chart.Left = 0;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(10);
// Add column series
Series series = chart.SeriesCollection.AddSeries();
series.ChartType = ChartType.Column2D;
series.Add(new double[] { 1, 17, 45, 5, 3, 20, 11, 23, 8, 19 });
series.HasDataLabel = true;
// Add line series for trend
series = chart.SeriesCollection.AddSeries();
series.ChartType = ChartType.Line;
series.Add(new double[] { 41, 7, 5, 45, 13, 10, 21, 13, 18, 9 });
// Add X-axis labels
XSeries xseries = chart.XValues.AddXSeries();
xseries.Add("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct");
// Configure axes
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.XAxis.Title.Caption = "Month";
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.YAxis.Title.Caption = "Sales ($K)";
// Configure plot area
chart.PlotArea.LineFormat.Color = Colors.DarkGray;
chart.PlotArea.LineFormat.Width = 1;
section.Add(chart);
// Render
PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();
renderer.PdfDocument.Save("MigraDocCharts.pdf");
```
--------------------------------
### Create Standard Text Annotations
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Annotations.md
Demonstrates how to instantiate a PdfTextAnnotation, set its metadata, and position it on a page using coordinate transformation.
```csharp
PdfTextAnnotation textAnnot = new PdfTextAnnotation();
textAnnot.Title = "This is the title";
textAnnot.Subject = "This is the subject";
textAnnot.Contents = "This is the contents of the annotation.\rThis is the 2nd line.";
textAnnot.Icon = PdfTextAnnotationIcon.Note;
gfx.DrawString("The first text annotation", font, XBrushes.Black, 30, 50, XStringFormats.Default);
XRect rect = gfx.Transformer.WorldToDefaultPage(new XRect(new XPoint(30, 60), new XSize(30, 30)));
textAnnot.Rectangle = new PdfRectangle(rect);
page.Annotations.Add(textAnnot);
```
--------------------------------
### Create and Format Tables with MigraDocCore
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
This C# code snippet demonstrates how to create tables in a PDF document using MigraDocCore. It covers defining columns, adding rows, styling cells with borders and shading, and merging cells horizontally and vertically. The output is saved as a PDF file.
```csharp
using MigraDocCore.DocumentObjectModel;
using MigraDocCore.DocumentObjectModel.Tables;
using MigraDocCore.Rendering;
using PdfSharpCore.Pdf;
Document document = new Document();
Section section = document.AddSection();
section.AddParagraph("Simple Table", "Heading1");
// Create table
Table table = new Table();
table.Borders.Width = 0.75;
// Define columns
Column column = table.AddColumn(Unit.FromCentimeter(2));
column.Format.Alignment = ParagraphAlignment.Center;
table.AddColumn(Unit.FromCentimeter(5));
// Add header row
Row row = table.AddRow();
row.Shading.Color = Colors.PaleGoldenrod;
row.Cells[0].AddParagraph("Item");
row.Cells[1].AddParagraph("Description");
// Add data rows
row = table.AddRow();
row.Cells[0].AddParagraph("1");
row.Cells[1].AddParagraph("First item description");
row = table.AddRow();
row.Cells[0].AddParagraph("2");
row.Cells[1].AddParagraph("Second item description with more text");
// Apply border styling
table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 1.5, Colors.Black);
section.Add(table);
// Demonstrate cell merging
section.AddParagraph("Cell Merging", "Heading1");
Table mergeTable = section.AddTable();
mergeTable.Borders.Visible = true;
mergeTable.AddColumn();
mergeTable.AddColumn();
mergeTable.AddColumn();
mergeTable.Rows.Height = 35;
// Merge cells horizontally
row = mergeTable.AddRow();
row.Cells[0].AddParagraph("Merged Right");
row.Cells[0].MergeRight = 1; // Merge with next cell
// Merge cells vertically
row = mergeTable.AddRow();
row.Cells[0].MergeDown = 1; // Merge with cell below
row.Cells[0].AddParagraph("Merged Down");
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row.Cells[1].AddParagraph("Normal");
row.Cells[2].AddParagraph("Normal");
mergeTable.AddRow();
mergeTable.Rows[2].Cells[1].AddParagraph("Below");
mergeTable.Rows[2].Cells[2].AddParagraph("Below");
// Render
PdfDocumentRenderer renderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();
renderer.PdfDocument.Save("MigraDocTables.pdf");
```
--------------------------------
### Create and Save PDF Document with MigraDocCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/index.md
This C# code snippet demonstrates the basic usage of MigraDocCore to create a simple PDF document. It includes adding sections, paragraphs, formatting text, and rendering the document to a PDF file. Dependencies include the MigraDocCore library.
```csharp
Document document = new Document();
Section section = document.AddSection();
section.AddParagraph("Hello, World!");
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);
paragraph.AddFormattedText("Hello, World!", TextFormat.Underline);
FormattedText ft = paragraph.AddFormattedText("Small text", TextFormat.Bold);
ft.Font.Size = 6;
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false,
PdfFontEmbedding.Always);
pdfRenderer.Document = document;
pdfRenderer.RenderDocument();
string filename = "HelloWorld.pdf";
pdfRenderer.PdfDocument.Save(filename);
```
--------------------------------
### Initialize MigraDocCore Document
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/Invoice.md
Initializes a new MigraDocCore document instance and sets metadata such as title, subject, and author. It serves as the entry point for document generation by calling helper methods for styling and content creation.
```csharp
public Document CreateDocument() {
this.document = new Document();
this.document.Info.Title = "A sample invoice";
this.document.Info.Subject = "Demonstrates how to create an invoice.";
this.document.Info.Author = "Stefan Lange";
DefineStyles();
CreatePage();
FillContent();
return this.document;
}
```
--------------------------------
### Working with Graphics Paths
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Demonstrates creating complex shapes using graphics paths, including open paths, closed paths, and clipping regions. It also shows how to convert text to a path for custom rendering.
```APIDOC
## Working with Graphics Paths
### Description
Demonstrates creating complex shapes using graphics paths, including open paths, closed paths, and clipping regions.
### Method
Not Applicable (Code Example)
### Endpoint
Not Applicable (Code Example)
### Parameters
Not Applicable (Code Example)
### Request Example
Not Applicable (Code Example)
### Response
#### Success Response (200)
Generates a PDF file named "GraphicsPaths.pdf" with the drawn paths.
#### Response Example
```csharp
// See C# code example for details.
```
## Convert Text to Path
### Description
Shows how to convert text into a graphics path and then draw it with custom pens and brushes.
### Method
Not Applicable (Code Example)
### Endpoint
Not Applicable (Code Example)
### Parameters
Not Applicable (Code Example)
### Request Example
Not Applicable (Code Example)
### Response
#### Success Response (200)
The text is rendered as a path in the "GraphicsPaths.pdf" file.
#### Response Example
```csharp
// See C# code example for details.
```
```
--------------------------------
### Create and Save a PDF Document with Text - C#
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/index.md
This snippet demonstrates how to create a new PDF document, add a page, draw text onto it using specified fonts and alignment, and then save the document to a file. It utilizes PdfSharpCore's drawing capabilities and XGraphics objects.
```csharp
using PdfSharp.Pdf;
using PdfSharp.Drawing;
// You’ll first need a PDF document:
PdfDocument document = new PdfDocument();
// And you need a page:
PdfPage page = document.AddPage();
// Drawing is done with an XGraphics object:
XGraphics gfx = XGraphics.FromPdfPage(page);
// Then you'll create a font:
XFont font = new XFont("Verdana", 20, XFontStyle.Bold);
// And you'll create an alignment to your text
XStringFormat stringFormat = new XStringFormat
{
Alignment = XStringAlignment.Center
};
// And you use that font and alignment to draw a string:
gfx.DrawString(
"Hello, World!", font, XBrushes.Black,
new XRect(0, 0, page.Width, page.Height),
stringFormat);
// When drawing is done, write the file:
string filename = "HelloWorld.pdf";
document.Save(filename);
```
--------------------------------
### Drawing and Transforming Images
Source: https://context7.com/ststeiger/pdfsharpcore/llms.txt
Shows how to load images from files and apply various transformations including scaling, rotation, and shearing using XGraphics.
```csharp
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// Load an image
XImage image = XImage.FromFile("sample.jpg");
// Draw image at original size
double x = (250 - image.PixelWidth * 72 / image.HorizontalResolution) / 2;
gfx.DrawImage(image, x, 20);
// Draw image scaled to specific dimensions
gfx.DrawImage(image, 20, 200, 250, 140);
// Draw image with rotation transformation
gfx.Save();
gfx.TranslateTransform(400, 150);
gfx.ScaleTransform(0.5);
gfx.RotateTransform(-25);
gfx.TranslateTransform(-image.PixelWidth / 2, -image.PixelHeight / 2);
gfx.DrawImage(image, 0, 0);
gfx.Restore();
// Draw image with shear transformation
gfx.Save();
gfx.TranslateTransform(400, 400);
gfx.ScaleTransform(-0.5, 0.5);
gfx.ShearTransform(-0.4, -0.3);
gfx.TranslateTransform(-image.PixelWidth / 2, -image.PixelHeight / 2);
gfx.DrawImage(image, 0, 0);
gfx.Restore();
document.Save("Images.pdf");
```
--------------------------------
### Create PDF Bookmarks using PdfOutline
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Bookmarks.md
This snippet demonstrates creating a PDF document, adding pages, and defining a root bookmark with nested sub-bookmarks. It utilizes the PdfOutline class to manage the document structure and saves the result to a file.
```csharp
PdfDocument document = new PdfDocument();
XFont font = new XFont("Verdana", 16);
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawString("Page 1", font, XBrushes.Black, 20, 50, XStringFormats.Default);
PdfOutline outline = document.Outlines.Add("Root", page, true, PdfOutlineStyle.Bold, XColors.Red);
for (int idx = 2; idx <= 5; idx++)
{
page = document.AddPage();
gfx = XGraphics.FromPdfPage(page);
string text = "Page " + idx;
gfx.DrawString(text, font, XBrushes.Black, 20, 50, XStringFormats.Default);
outline.Outlines.Add(text, page, true);
}
const string filename = "Bookmarks_tempfile.pdf";
document.Save(filename);
```
--------------------------------
### Create Minimalist MigraDocCore Document
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloWorld.md
The CreateDocument method constructs a basic document structure, including a section and a formatted paragraph with CMYK color settings.
```csharp
static Document CreateDocument()
{
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);
paragraph.AddFormattedText("Hello, World!", TextFormat.Bold);
return document;
}
```
--------------------------------
### Create Booklet from PDF using PDFSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Booklet.md
This code snippet demonstrates how to take an existing PDF document and impose its pages into a booklet format. It calculates the necessary number of sheets, handles blank pages for non-divisible page counts, and uses XGraphics to draw source pages onto new landscape pages.
```csharp
PdfDocument outputDocument = new PdfDocument();
outputDocument.PageLayout = PdfPageLayout.SinglePage;
XGraphics gfx;
XPdfForm form = XPdfForm.FromFile(filename);
double extWidth = form.PixelWidth;
double extHeight = form.PixelHeight;
int inputPages = form.PageCount;
int sheets = inputPages / 4;
if (sheets * 4 < inputPages) sheets += 1;
int allpages = 4 * sheets;
int vacats = allpages - inputPages;
for (int idx = 1; idx <= sheets; idx += 1)
{
PdfPage page = outputDocument.AddPage();
page.Orientation = PageOrientation.Landscape;
page.Width = 2 * extWidth;
page.Height = extHeight;
double width = page.Width;
double height = page.Height;
gfx = XGraphics.FromPdfPage(page);
XRect box;
if (vacats > 0) vacats -= 1;
else
{
form.PageNumber = allpages + 2 * (1 - idx);
box = new XRect(0, 0, width / 2, height);
gfx.DrawImage(form, box);
}
form.PageNumber = 2 * idx - 1;
box = new XRect(width / 2, 0, width / 2, height);
gfx.DrawImage(form, box);
page = outputDocument.AddPage();
page.Orientation = PageOrientation.Landscape;
page.Width = 2 * extWidth;
page.Height = extHeight;
gfx = XGraphics.FromPdfPage(page);
form.PageNumber = 2 * idx;
box = new XRect(0, 0, width / 2, height);
gfx.DrawImage(form, box);
if (vacats > 0) vacats -= 1;
else
{
form.PageNumber = allpages + 1 - 2 * idx;
box = new XRect(width / 2, 0, width / 2, height);
gfx.DrawImage(form, box);
}
}
outputDocument.Save("Booklet.pdf");
```