### Hello World PDF creation with PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/index.md
This snippet shows the essential steps to create a PDF document using PdfSharpCore: create a PdfDocument, add a PdfPage, obtain an XGraphics object, create an XFont and XStringFormat, draw a string, and save the document. It is the core example from the 'First steps' section, demonstrating the basic API usage.
```cs
// 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);
```
--------------------------------
### Custom font resolver implementation (MyFontResolver)
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/FontResolver.md
Complete example of a custom font resolver implementing IFontResolver. It maps family names to font files and reads the font data from a path. This implementation is not complete but serves as a starting point. Note that the path is hardcoded as "my path" and must be adjusted.
```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())
{
try
{
using(var fs = File.OpenRead(faceNamePath))
{
fs.CopyTo(ms);
ms.Position = 0;
return ms.ToArray();
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw new Exception($"No Font File Found - " + faceNamePath);
}
}
}
}
```
--------------------------------
### Create and save a PdfSharpCore PdfDocument
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/MixMigraDocCoreAndPDFsharpCore.md
Creates a PdfSharpCore PdfDocument, sets metadata, calls SamplePage1 and SamplePage2, and saves the document to a GUID-named PDF file. The filename is overwritten with a new GUID, so the initial filename is not used.
```cs
static void Main()
{
DateTime now = DateTime.Now;
string filename = "MixMigraDocCoreAndPdfSharpCore.pdf";
filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
PdfDocument document = new PdfDocument();
document.Info.Title = "PdfSharpCore XGraphic Sample";
document.Info.Author = "Stefan Lange";
document.Info.Subject = "Created with code snippets that show the use of graphical functions";
document.Info.Keywords = "PdfSharpCore, XGraphics";
SamplePage1(document);
SamplePage2(document);
Debug.WriteLine("seconds=" + (DateTime.Now - now).TotalSeconds.ToString());
// Save the document...
document.Save(filename);
}
```
--------------------------------
### DrawPie with XGraphics
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Draws four pie slices using XGraphics.DrawPie with varying start angles and sweep angles. Uses a DarkBlue pen and Gold brush.
```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);
}
```
--------------------------------
### DefineContentSection: Set up headers, footers, and page numbering
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Configures a new section with odd/even headers and footers, starting page number at 1. Adds a page field to the footer and clones the paragraph for the even page footer; cloning is required to avoid an exception because an object cannot belong to multiple parents.
```cs
///
/// 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());
}
```
--------------------------------
### Hello World sample: Create a document with MigraDocCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/index.md
Shows the basic steps to create a PDF document: add a section, paragraphs, formatted text, and render to PDF. Uses PdfDocumentRenderer with PdfFontEmbedding.Always and saves to a file.
```cs
// We start with a new document:
Document document = new Document();
// With MigraDocCore, we don’t add pages, we add sections (at least one):
Section section = document.AddSection();
// Adding text is simple:
section.AddParagraph("Hello, World!");
// Adding empty paragraphs is even simpler:
section.AddParagraph();
// Store the newly created object for modification:
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);
paragraph.AddFormattedText("Hello, World!", TextFormat.Underline);
// AddFormattedText also returns an object:
FormattedText ft = paragraph.AddFormattedText("Small text", TextFormat.Bold);
ft.Font.Size = 6;
// And there’s much more that can be added: AddTable, AddImage, AddHyperlink, AddBookmark, AddPageField, AddPageBreak, ...
// With MigraDocCore you can create PDF or RTF. Just select the appropriate renderer:
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false,
PdfFontEmbedding.Always);
// Pass the document to the renderer:
pdfRenderer.Document = document;
// Let the renderer do its job:
pdfRenderer.RenderDocument();
// Save the PDF to a file:
string filename = "HelloWorld.pdf";
pdfRenderer.PdfDocument.Save(filename);
```
--------------------------------
### Draw an arc with DrawArc
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Draws an arc within a specified rectangle, starting at 190 degrees and sweeping 200 degrees.
```C#
void DrawArc(XGraphics gfx, int number)
{
BeginBox(gfx, number, "DrawArc");
XPen pen = new XPen(XColors.Plum, 4.7);
gfx.DrawArc(pen, 0, 0, 250, 140, 190, 200);
EndBox(gfx);
}
```
--------------------------------
### Main program: Create PDF document and add sample pages
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Creates a temporary PDF file, sets document metadata, adds demonstration pages for each graphical primitive, and saves the document.
```C#
static void Main()
{
// Create a temporary file
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";
// Create demonstration pages
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());
// Save the s_document...
s_document.Save(filename);
}
```
--------------------------------
### Main method: Create and render a MigraDocCore document to PDF
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloWorld.md
This snippet shows the entry point for a MigraDocCore Hello World program. It creates a document, sets the CMYK color mode, configures Unicode and font embedding settings, renders the document to PDF, and saves it as 'HelloWorld.pdf'. The 'unicode' flag and 'embedding' setting apply to all fonts used in the PDF but have no effect on the RTF renderer.
```csharp
static void Main(string[] args)
{
// Create a MigraDocCore document
Document document = CreateDocument();
document.UseCmykColor = true;
// ===== Unicode encoding and font program embedding in MigraDocCore is demonstrated here =====
// A flag indicating whether to create a Unicode PDF or a WinAnsi PDF file.
// This setting applies to all fonts used in the PDF document.
// This setting has no effect on the RTF renderer.
const bool unicode = false;
// An enum indicating whether to embed fonts or not.
// This setting applies to all font programs used in the document.
// This setting has no effect on the RTF renderer.
// (The term 'font program' is used by Adobe for a file containing a font. Technically a 'font file'
// is a collection of small programs and each program renders the glyph of a character when executed.
// Using a font in PdfSharpCore may lead to the embedding of one or more font programs, because each outline
// (regular, bold, italic, bold+italic, ...) has its own font program)
const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
// ========================================================================================
// Create a renderer for the MigraDocCore document.
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);
// Associate the MigraDocCore document with a renderer
pdfRenderer.Document = document;
// Layout and render document to PDF
pdfRenderer.RenderDocument();
// Save the document...
const string filename = "HelloWorld.pdf";
pdfRenderer.PdfDocument.Save(filename);
}
```
--------------------------------
### DrawPath closed with CloseFigure
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Strokes a closed path by calling CloseFigure() before DrawPath, using the same dashed pen as the open path example.
```csharp
void DrawPathClosed(XGraphics gfx, int number)
{
BeginBox(gfx, number, "DrawPath (closed)");
XPen pen = new XPen(XColors.Navy, Math.PI);
pen.DashStyle = XDashStyle.Dash;
XGraphicsPath path = new XGraphicsPath();
path.AddLine(10, 120, 50, 60);
path.AddArc(50, 20, 110, 80, 180, 180);
path.AddLine(160, 60, 220, 100);
path.CloseFigure();
gfx.DrawPath(pen, path);
EndBox(gfx);
}
```
--------------------------------
### Main method: render and save PDF
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloMigraDocCore.md
Entry point that creates a MigraDocCore document, writes a DDL file, renders it to PDF with embedded fonts, and saves the result as HelloMigraDoc.pdf.
```csharp
static void Main()
{
// Create a MigraDocCore document
Document document = Documents.CreateDocument();
//string ddl = MigraDocCore.DocumentObjectModel.IO.DdlWriter.WriteToString(document);
MigraDocCore.DocumentObjectModel.IO.DdlWriter.WriteToFile(document, "MigraDocCore.mdddl");
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();
// Save the document...
string filename = "HelloMigraDoc.pdf";
renderer.PdfDocument.Save(filename);
}
```
--------------------------------
### Stub for PNG image export
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/ExportImages.md
Stub for exporting non-JPEG images (e.g., FlateDecode) as PNG. Reads image dimensions and bits per component but does not implement conversion. Intended as a starting point for developers.
```csharp
static void ExportAsPngImage(PdfDictionary image, ref int count)
{
int width = image.Elements.GetInteger(PdfImage.Keys.Width);
int height = image.Elements.GetInteger(PdfImage.Keys.Height);
int bitsPerComponent = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);
// TODO: You can put the code here that converts vom PDF internal image format to a Windows bitmap
// and use GDI+ to save it in PNG format.
// It is the work of a day or two for the most important formats. Take a look at the file
// PdfSharpCore.Pdf.Advanced/PdfImage.cs to see how we create the PDF image formats.
// We don't need that feature at the moment and therefore will not implement it.
// If you write the code for exporting images I would be pleased to publish it in a future release
// of PdfSharpCore.
}
```
--------------------------------
### DrawTextAlignment: align text with XStringFormat
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Draws text at nine positions inside a 250x140 rectangle by changing XStringFormat.Alignment and LineAlignment. Uses a Verdana 10 font and purple brush, with a yellow-green rectangle and guide lines.
```csharp
void DrawTextAlignment(XGraphics gfx, int number)
{
BeginBox(gfx, number, "Text Alignment");
XRect rect = new XRect(0, 0, 250, 140);
XFont font = new XFont("Verdana", 10);
XBrush brush = XBrushes.Purple;
XStringFormat format = new XStringFormat();
gfx.DrawRectangle(XPens.YellowGreen, rect);
gfx.DrawLine(XPens.YellowGreen, rect.Width / 2, 0, rect.Width / 2, rect.Height);
gfx.DrawLine(XPens.YellowGreen, 0, rect.Height / 2, rect.Width, rect.Height / 2);
gfx.DrawString("TopLeft", font, brush, rect, format);
format.Alignment = XStringAlignment.Center;
gfx.DrawString("TopCenter", font, brush, rect, format);
format.Alignment = XStringAlignment.Far;
gfx.DrawString("TopRight", font, brush, rect, format);
format.LineAlignment = XLineAlignment.Center;
format.Alignment = XStringAlignment.Near;
gfx.DrawString("CenterLeft", font, brush, rect, format);
format.Alignment = XStringAlignment.Center;
gfx.DrawString("Center", font, brush, rect, format);
format.Alignment = XStringAlignment.Far;
gfx.DrawString("CenterRight", font, brush, rect, format);
format.LineAlignment = XLineAlignment.Far;
format.Alignment = XStringAlignment.Near;
gfx.DrawString("BottomLeft", font, brush, rect, format);
format.Alignment = XStringAlignment.Center;
gfx.DrawString("BottomCenter", font, brush, rect, format);
format.Alignment = XStringAlignment.Far;
gfx.DrawString("BottomRight", font, brush, rect, format);
EndBox(gfx);
}
```
--------------------------------
### Create a PDF with 'Hello World!' using PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/README.md
Creates a simple PDF file with the text 'Hello World!' using PdfSharpCore. Requires a .NET 6 console app with top-level statements. Sets a global font resolver, adds a page, draws a bold Arial string centered on the page, and saves the document as 'helloworld.pdf'.
```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");
```
--------------------------------
### CreateDocument method: Build a minimal MigraDocCore document
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/HelloWorld.md
This snippet defines the CreateDocument method that constructs a minimal MigraDocCore document. It adds a section and a paragraph, sets the font color to CMYK (100, 30, 20, 50), and adds bold formatted text 'Hello, World!'. The method returns the document for rendering.
```csharp
///
/// Creates an absolutely minimalistic document.
///
static Document CreateDocument()
{
// Create a new MigraDocCore document
Document document = new Document();
// Add a section to the document
Section section = document.AddSection();
// Add a paragraph to the section
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);
// Add some text to the paragraph
paragraph.AddFormattedText("Hello, World!", TextFormat.Bold);
return document;
}
```
--------------------------------
### DrawPage entry point for Text sample
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Entry point for the Text sample. Creates an XGraphics object from the page, draws a title, and calls the three text-related helper methods.
```csharp
public void DrawPage(PdfPage page)
{
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawTitle(page, gfx, "Text");
DrawText(gfx, 1);
DrawTextAlignment(gfx, 2);
MeasureText(gfx, 3);
}
```
--------------------------------
### Set PDF color mode to CMYK and draw rectangles
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/ColorsCMYK.md
Opens a PDF, sets ColorMode to Cmyk, ensures PDF version 1.4 for transparency, and draws rectangles with XColor.FromCmyk. The example includes multiple DrawRectangle calls with different CMYK values.
```C#
PdfDocument document = PdfReader.Open(filename);
document.Options.ColorMode = PdfColorMode.Cmyk;
// Set version to PDF 1.4 (Acrobat 5) because we use transparency.
if (document.Version < 14)
document.Version = 14;
PdfPage page = document.Pages[0];
// Get an XGraphics object for drawing beneath the existing content
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(1, 0.68, 0, 0.12)), new XRect(30, 60, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0, 0.70, 1, 0)), new XRect(550, 60, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0, 0, 0, 0)), new XRect(90, 100, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0, 0, 0, 0)), new XRect(150, 100, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0.7, 0, 0.70, 1, 0)), new XRect(90, 100, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0.5, 0, 0.70, 1, 0)), new XRect(150, 100, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0.35, 0.15, 0, 0.08)), new XRect(50, 360, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0.25, 0.10, 0, 0.05)), new XRect(150, 360, 50, 50));
gfx.DrawRectangle(new XSolidBrush(XColor.FromCmyk(0.15, 0.05, 0, 0)), new XRect(250, 360, 50, 50));
```
--------------------------------
### MeasureText: get font metrics and draw transparent text
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Measures a string with a 95-point Times New Roman font and draws colored rectangles for effective ascent, descent, and leading. Also draws the text half transparent using an XColor with alpha 0.6.
```csharp
void MeasureText(XGraphics gfx, int number)
{
BeginBox(gfx, number, "Measure Text");
const XFontStyle style = XFontStyle.Regular;
XFont font = new XFont("Times New Roman", 95, style);
const string text = "Hallo";
const double x = 20, y = 100;
XSize size = gfx.MeasureString(text, font);
double lineSpace = font.GetHeight(gfx);
int cellSpace = font.FontFamily.GetLineSpacing(style);
int cellAscent = font.FontFamily.GetCellAscent(style);
int cellDescent = font.FontFamily.GetCellDescent(style);
int cellLeading = cellSpace - cellAscent - cellDescent;
// Get effective ascent
double ascent = lineSpace * cellAscent / cellSpace;
gfx.DrawRectangle(XBrushes.Bisque, x, y - ascent, size.Width, ascent);
// Get effective descent
double descent = lineSpace * cellDescent / cellSpace;
gfx.DrawRectangle(XBrushes.LightGreen, x, y, size.Width, descent);
// Get effective leading
double leading = lineSpace * cellLeading / cellSpace;
gfx.DrawRectangle(XBrushes.Yellow, x, y + descent, size.Width, leading);
// Draw text half transparent
XColor color = XColors.DarkSlateBlue;
color.A = 0.6;
gfx.DrawString(text, font, new XSolidBrush(color), x, y);
EndBox(gfx);
}
```
--------------------------------
### Page_Load: Create PDF and send to browser
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Clock.md
This is the framework for an .aspx page that returns a PDF file. It creates a new PdfDocument, sets metadata, adds a page, draws the clock, and sends the PDF to the browser via Response.BinaryWrite.
```cs
void Page_Load(object sender, EventArgs e)
{
// Create new PDF document
PdfDocument document = new PdfDocument();
this.time = document.Info.CreationDate;
document.Info.Title = "PdfSharpCore Clock Demo";
document.Info.Author = "Stefan Lange";
document.Info.Subject = "Server time: " +
this.time.ToString("F", CultureInfo.InvariantCulture);
// Create new page
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(200);
page.Height = XUnit.FromMillimeter(200);
// Create graphics object and draw clock
XGraphics gfx = XGraphics.FromPdfPage(page);
RenderClock(gfx);
// Send PDF to browser
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}
```
--------------------------------
### DrawPage - Main entry point for image samples
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Entry point for the Images sample. Creates an XGraphics object from the page, draws the title, and calls each image-drawing helper method in sequence.
```csharp
public void DrawPage(PdfPage page)
{
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawTitle(page, gfx, "Images");
DrawImage(gfx, 1);
DrawImageScaled(gfx, 2);
DrawImageRotated(gfx, 3);
DrawImageSheared(gfx, 4);
DrawGif(gfx, 5);
DrawPng(gfx, 6);
DrawTiff(gfx, 7);
DrawFormXObject(gfx, 8);
}
```
--------------------------------
### Variant4: Concatenate PDFs and add unique graphics to each page
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/ConcatenateDocuments.md
This C# example opens multiple PDF files, imports each page twice into an output document, and appends unique page numbers using XGraphics. It demonstrates that external pages are shared, while added graphics are unique per page. The output is saved as 'ConcatenatedDocument4_tempfile.pdf'.
```csharp
///
/// This sample is the combination of Variant2 and Variant3. It shows that you
/// can add external pages more than once and still add individual graphics on
/// each page. The external content is shared among the pages, the new graphics
/// are unique to each page. You can check this by comparing the file size
/// of Variant3 and Variant4.
///
static void Variant4()
{
// Get some file names
string[] files = GetFiles();
// Open the output document
PdfDocument outputDocument = new PdfDocument();
// For checking the file size uncomment next line.
//outputDocument.Options.CompressContentStreams = true;
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);
}
```
--------------------------------
### DrawPage for Paths sample
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Entry point for the Paths sample. Creates an XGraphics object, draws a title, and calls each path-drawing method in sequence.
```csharp
public void DrawPage(PdfPage page)
{
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawTitle(page, gfx, "Paths");
DrawPathOpen(gfx, 1);
DrawPathClosed(gfx, 2);
DrawPathAlternateAndWinding(gfx, 3);
DrawGlyphs(gfx, 5);
DrawClipPath(gfx, 6);
}
```
--------------------------------
### Create a minimal document with an image in MigraDocCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/Images.md
Creates a minimal MigraDocCore document with a section, a paragraph containing formatted text, and an image added via section.AddImage(). The image path is relative to the document's location.
```csharp
///
/// Creates an absolutely minimalistic document.
///
static Document CreateDocument()
{
// Create a new MigraDocCore document
Document document = new Document();
// Add a section to the document
Section section = document.AddSection();
// Add a paragraph to the section
Paragraph paragraph = section.AddParagraph();
// Add some text to the paragraph
paragraph.AddFormattedText("Hello, World!", TextFormat.Italic);
section.AddImage("../../SomeImage.png");
return document;
}
```
--------------------------------
### Create PDF bookmarks with PdfOutline
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Bookmarks.md
Creates a PDF with bookmarks (outlines) using PdfSharpCore. Adds a root bookmark with bold style and red color, then adds sub-bookmarks for pages 2-5. Saves the document as 'Bookmarks_tempfile.pdf'.
```csharp
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Create a font
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. You can set the style and the color.
PdfOutline outline = document.Outlines.Add("Root", page, true, PdfOutlineStyle.Bold, XColors.Red);
// Create some more pages
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
outline.Outlines.Add(text, page, true);
}
// Save the document...
const string filename = "Bookmarks_tempfile.pdf";
document.Save(filename);
```
--------------------------------
### Create and save PDF with PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/HelloWorld.md
Demonstrates the basic workflow to create a PDF document, add a page, draw text, and save it. Sets the document title to 'Created with PdfSharpCore', uses Verdana bold italic font size 20, and centers the text on the page.
```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);
}
}
}
```
--------------------------------
### Create an XForm and draw graphics on it
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/XForms.md
Step 1: Creates an XForm object with specified dimensions, draws a transparent rectangle, text, Bézier curves, a GIF image, and an XPdfForm. The form is bound to the target document when created, and the XGraphics object must be disposed after drawing.
```cs
// Create an empty XForm object with the specified width and height
// A form is bound to its target document when it is created. The reason is that the form can
// share fonts and other objects with its target document.
XForm form = new XForm(document, XUnit.FromMillimeter(70), XUnit.FromMillimeter(55));
// Create an XGraphics object for drawing the contents of the form.
XGraphics formGfx = XGraphics.FromForm(form);
// Draw a large transparent rectangle to visualize the area the form occupies
XColor back = XColors.Orange;
back.A = 0.2;
XSolidBrush brush = new XSolidBrush(back);
formGfx.DrawRectangle(brush, -10000, -10000, 20000, 20000);
// On a form you can draw...
// ... text
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;
// ... graphics like Bézier curves
formGfx.DrawBeziers(pen, XPoint.ParsePoints("30,120 80,20 100,140 175,33.3"));
// ... raster images like GIF files
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);
// ... and forms like XPdfForm objects
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);
// When you finished drawing on the form, dispose the XGraphic object.
formGfx.Dispose();
```
--------------------------------
### Create PDF with all predefined page sizes
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/PageSizes.md
Creates a PDF document with pages for each predefined PageSize value, skipping Undefined. For each size, it adds a portrait page and a landscape page, drawing the size name centered on each page. Saves the result to PageSizes_tempfile.pdf.
```csharp
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Create a font
XFont font = new XFont("Times", 25, XFontStyle.Bold);
PageSize[] pageSizes = (PageSize[])Enum.GetValues(typeof(PageSize));
foreach (PageSize pageSize in pageSizes)
{
if (pageSize == PageSize.Undefined)
continue;
// One page in Portrait...
PdfPage page = document.AddPage();
page.Size = pageSize;
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawString(pageSize.ToString(), font, XBrushes.DarkRed,
new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
// ... and one in Landscape orientation.
page = document.AddPage();
page.Size = pageSize;
page.Orientation = PageOrientation.Landscape;
gfx = XGraphics.FromPdfPage(page);
gfx.DrawString(pageSize + " (landscape)", font,
XBrushes.DarkRed, new XRect(0, 0, page.Width, page.Height),
XStringFormats.Center);
}
// Save the document...
const string filename = "PageSizes_tempfile.pdf";
document.Save(filename);
```
--------------------------------
### Split PDF into single-page documents with PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/SplitDocument.md
Opens a PDF in Import mode, then for each page creates a new PdfDocument, copies the page with AddPage, and saves it as a separate file named "{original} - Page {n}_tempfile.pdf". The sample copies a fresh PDF from a relative path before opening it.
```csharp
// Get a fresh copy of the sample PDF file
const string filename = "Portable Document Format.pdf";
File.Copy(Path.Combine("../../../../../PDFs/", filename),
Path.Combine(Directory.GetCurrentDirectory(), filename), true);
// Open the file
PdfDocument inputDocument = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
string name = Path.GetFileNameWithoutExtension(filename);
for (int idx = 0; idx < inputDocument.PageCount; idx++)
{
// Create new document
PdfDocument outputDocument = new PdfDocument();
outputDocument.Version = inputDocument.Version;
outputDocument.Info.Title =
String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
outputDocument.Info.Creator = inputDocument.Info.Creator;
// Add the page and save it
outputDocument.AddPage(inputDocument.Pages[idx]);
outputDocument.Save(String.Format("{0} - Page {1}_tempfile.pdf", name, idx + 1));
}
```
--------------------------------
### Create multi-page PDF with LayoutHelper and AddPage()
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/MultiplePages.md
The LayoutHelper class manages line positions and automatically creates a new A4 page when the current position plus the required height exceeds the bottom margin. The sample code uses it to draw 666 lines of text with random headers, saving the result to MultiplePages.pdf. Note that the sample assumes short texts that fit on one line; for large documents, MigraDocCore is recommended.
```cs
public class LayoutHelper
{
private readonly PdfDocument _document;
private readonly XUnit _topPosition;
private readonly XUnit _bottomMargin;
private XUnit _currentPosition;
public LayoutHelper(PdfDocument document, XUnit topPosition, XUnit bottomMargin)
{
_document = document;
_topPosition = topPosition;
_bottomMargin = bottomMargin;
// Set a value outside the page - a new page will be created on the first request.
_currentPosition = bottomMargin + 10000;
}
public XUnit GetLinePosition(XUnit requestedHeight)
{
return GetLinePosition(requestedHeight, -1f);
}
public XUnit GetLinePosition(XUnit requestedHeight, XUnit requiredHeight)
{
XUnit required = requiredHeight == -1f ? requestedHeight : requiredHeight;
if (_currentPosition + required > _bottomMargin)
CreatePage();
XUnit result = _currentPosition;
_currentPosition += requestedHeight;
return result;
}
public XGraphics Gfx { get; private set; }
public PdfPage Page { get; private set; }
void CreatePage()
{
Page = _document.AddPage();
Page.Size = PageSize.A4;
Gfx = XGraphics.FromPdfPage(Page);
_currentPosition = _topPosition;
}
}
```
```cs
PdfDocument document = new PdfDocument();
// Sample uses DIN A4, page height is 29.7 cm. We use margins of 2.5 cm.
LayoutHelper helper = new LayoutHelper(document, XUnit.FromCentimeter(2.5), XUnit.FromCentimeter(29.7 - 2.5));
XUnit left = XUnit.FromCentimeter(2.5);
// Random generator with seed value, so created document will always be the same.
Random rand = new Random(42);
const int headerFontSize = 20;
const int normalFontSize = 10;
XFont fontHeader = new XFont("Verdana", headerFontSize, XFontStyle.BoldItalic);
XFont fontNormal = new XFont("Verdana", normalFontSize, XFontStyle.Regular);
const int totalLines = 666;
bool washeader = false;
for (int line = 0; line < totalLines; ++line)
{
bool isHeader = line == 0 || !washeader && line < totalLines - 1 && rand.Next(15) == 0;
washeader = isHeader;
// We do not want a single header at the bottom of the page,
// so if we have a header we require space for header and a normal text line.
XUnit top = helper.GetLinePosition(isHeader ? headerFontSize + 5: normalFontSize + 2, isHeader ? headerFontSize + 5 + normalFontSize : normalFontSize);
helper.Gfx.DrawString(isHeader ? "Sed massa libero, semper a nisi nec" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
isHeader ? fontHeader : fontNormal, XBrushes.Black, left, top, XStringFormats.TopLeft);
}
// Save the document...
const string filename = "MultiplePages.pdf";
document.Save(filename);
```
--------------------------------
### BeginBox and EndBox: Draw rounded sample boxes
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Draws a rounded box with a shadow and gradient background, then saves the graphics state and translates the origin for drawing content inside. EndBox restores the saved state. The box position is determined by the sample number.
```csharp
public void BeginBox(XGraphics gfx, int number, string title)
{
const int dEllipse = 15;
XRect rect = new XRect(0, 20, 300, 200);
if (number % 2 == 0)
rect.X = 300 - 5;
rect.Y = 40 + ((number - 1) / 2) * (200 - 5);
rect.Inflate(-10, -10);
XRect rect2 = rect;
rect2.Offset(this.borderWidth, this.borderWidth);
gfx.DrawRoundedRectangle(
new XSolidBrush(this.shadowColor),
rect2,
new XSize(dEllipse + 8, dEllipse + 8)
);
XLinearGradientBrush brush = new XLinearGradientBrush(
rect, this.backColor, this.backColor2, XLinearGradientMode.Vertical);
gfx.DrawRoundedRectangle(this.borderPen, brush, rect, new XSize(dEllipse, dEllipse));
rect.Inflate(-5, -5);
XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
gfx.DrawString(title, font, XBrushes.Navy, rect, XStringFormats.TopCenter);
rect.Inflate(-10, -5);
rect.Y += 20;
rect.Height -= 20;
this.state = gfx.Save();
gfx.TranslateTransform(rect.X, rect.Y);
}
public void EndBox(XGraphics gfx)
{
gfx.Restore(this.state);
}
```
--------------------------------
### DrawPage for Shapes sample
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/Graphics.md
Entry point for the Shapes sample. Creates an XGraphics object from the page, draws a title, and calls each shape-drawing method in sequence.
```csharp
public void DrawPage(PdfPage page)
{
XGraphics gfx = XGraphics.FromPdfPage(page);
DrawTitle(page, gfx, "Shapes");
DrawRectangle(gfx, 1);
DrawRoundedRectangle(gfx, 2);
DrawEllipse(gfx, 3);
DrawPolygon(gfx, 4);
DrawPie(gfx, 5);
DrawClosedCurve(gfx, 6);
}
```
--------------------------------
### CreateDocument method
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/MigraDocCore/samples/Invoice.md
Creates a new MigraDocCore Document, sets its title, subject, and author, then calls DefineStyles, CreatePage, and FillContent before returning the document.
```csharp
public Document CreateDocument()
{
// Create a new MigraDocCore document
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;
}
```
--------------------------------
### Protect a PDF with passwords and permissions using PdfSharpCore
Source: https://github.com/ststeiger/pdfsharpcore/blob/master/docs/PdfSharpCore/samples/ProtectDocument.md
Opens an existing PDF, sets user and owner passwords (which automatically enables 128-bit encryption), restricts permissions, and saves the protected file. The provided password when opening is ignored. The 40-bit encryption level is commented out as not recommended unless needed for compatibility.
```csharp
// Get a fresh copy of the sample PDF file
const string filenameSource = "HelloWorld.pdf";
const string filenameDest = "HelloWorld_tempfile.pdf";
File.Copy(Path.Combine("../../../../../PDFs/", filenameSource),
Path.Combine(Directory.GetCurrentDirectory(), filenameDest), true);
// Open an existing document. Providing an unrequired password is ignored.
PdfDocument document = PdfReader.Open(filenameDest, "some text");
PdfSecuritySettings securitySettings = document.SecuritySettings;
// Setting one of the passwords automatically sets the security level to
// PdfDocumentSecurityLevel.Encrypted128Bit.
securitySettings.UserPassword = "user";
securitySettings.OwnerPassword = "owner";
// Don't use 40 bit encryption unless needed for compatibility
//securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;
// Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = false;
securitySettings.PermitModifyDocument = true;
securitySettings.PermitPrint = false;
// Save the document...
document.Save(filenameDest);
```