### Complete Drawing Example with PdfPen and Brushes Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md A comprehensive example demonstrating drawing various shapes and text with different brushes and pens, including solid fill, linear gradient, and dashed outlines. ```csharp PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); // Solid fill with border PdfSolidBrush fillBrush = new PdfSolidBrush(Color.LightBlue); PdfPen borderPen = new PdfPen(Color.Navy, 2); page.Canvas.DrawRectangle(borderPen, fillBrush, new RectangleF(10, 10, 100, 80)); // Linear gradient PdfLinearGradientBrush gradientBrush = new PdfLinearGradientBrush( new PointF(150, 10), new PointF(250, 90), Color.Yellow, Color.Red); page.Canvas.DrawEllipse(gradientBrush, new RectangleF(150, 10, 100, 80)); // Dashed circle outline PdfPen dashedPen = new PdfPen(Color.Green, 1.5f); dashedPen.DashStyle = PdfDashStyle.Dash; page.Canvas.DrawEllipse(dashedPen, new RectangleF(280, 10, 80, 80)); // Text with different colors page.Canvas.DrawString("Text 1", font, PdfBrushes.Blue, 10, 120); page.Canvas.DrawString("Text 2", font, PdfBrushes.Red, 10, 150); doc.SaveToFile("output.pdf"); ``` -------------------------------- ### PdfTextureBrush Example Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Shows how to create and use a PdfTextureBrush to fill a rectangle with a specified image pattern. ```APIDOC ## PdfTextureBrush Example ### Description Example of using a texture brush to fill a rectangle. ### Code Example ```csharp PdfImage textureImage = PdfImage.FromFile("pattern.png"); PdfTextureBrush textureBrush = new PdfTextureBrush(textureImage); // Fill rectangle with texture page.Canvas.DrawRectangle(textureBrush, new RectangleF(10, 10, 200, 150)); ``` ``` -------------------------------- ### Create a PdfButtonField Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfFormFields.md Example of creating a button field, setting its bounds, text, colors, and tooltip. ```csharp PdfButtonField button = new PdfButtonField(doc.Pages[0], "submitBtn"); button.Bounds = new RectangleF(100, 550, 80, 30); button.Text = "Submit"; button.BackColor = Color.LightGray; button.ForeColor = Color.Black; button.ToolTip = "Click to submit the form"; doc.Form.Fields.Add(button); ``` -------------------------------- ### Predefined Brushes Usage Example Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Demonstrates using predefined solid color brushes from PdfBrushes class to draw text and rectangles. ```csharp page.Canvas.DrawString("Red text", font, PdfBrushes.Red, 10, 10); page.Canvas.DrawRectangle(PdfBrushes.LightBlue, rect); ``` -------------------------------- ### Create and Configure a PdfComboBoxField Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfFormFields.md Example of creating a ComboBox field, setting its bounds, adding items, and configuring selection behavior. ```csharp PdfDocument doc = new PdfDocument(); doc.LoadFromFile("form_template.pdf"); doc.AllowCreateForm = true; PdfComboBoxField combo = new PdfComboBoxField(doc.Pages[0], "country"); combo.Bounds = new RectangleF(100, 450, 200, 25); combo.Items.Add("USA", "United States"); combo.Items.Add("CAN", "Canada"); combo.Items.Add("MEX", "Mexico"); combo.SelectedIndex = 0; combo.CommitOnSelChange = true; doc.Form.Fields.Add(combo); doc.SaveToFile("form_with_combobox.pdf"); ``` -------------------------------- ### Create a PdfListBoxField Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfFormFields.md Example of creating a ListBox field, setting its bounds, adding items, and enabling multi-select functionality. ```csharp PdfListBoxField listBox = new PdfListBoxField(doc.Pages[0], "skills"); listBox.Bounds = new RectangleF(100, 500, 200, 80); listBox.Items.Add("C#", "C#"); listBox.Items.Add("VB.NET", "VB.NET"); listBox.Items.Add("Java", "Java"); listBox.Multiselect = true; doc.Form.Fields.Add(listBox); ``` -------------------------------- ### PdfSolidBrush Examples Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Demonstrates how to use PdfSolidBrush for drawing text and shapes with solid colors, including using predefined colors from PdfBrushes. ```APIDOC ## PdfSolidBrush Examples ### Description Examples of using PdfSolidBrush for text and shape fills, and with predefined colors. ### Code Examples **Text with solid brush:** ```csharp PdfPageBase page = doc.Pages.Add(); PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 14f); PdfSolidBrush brush = new PdfSolidBrush(Color.Blue); page.Canvas.DrawString("Solid blue text", font, brush, 10, 10); ``` **Shape with solid fill:** ```csharp PdfSolidBrush fillBrush = new PdfSolidBrush(Color.LightGreen); page.Canvas.DrawRectangle(fillBrush, new RectangleF(10, 50, 100, 100)); // With border PdfPen borderPen = new PdfPen(Color.DarkGreen, 2); page.Canvas.DrawRectangle(borderPen, fillBrush, new RectangleF(10, 50, 100, 100)); ``` **Using predefined colors:** ```csharp // PdfBrushes class provides common colors page.Canvas.DrawString("Red text", font, PdfBrushes.Red, 10, 10); page.Canvas.DrawString("Blue text", font, PdfBrushes.Blue, 10, 30); page.Canvas.DrawString("Green text", font, PdfBrushes.Green, 10, 50); ``` ``` -------------------------------- ### DrawImage Examples Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfCanvas.md Illustrates how to draw both PDF images and .NET Image objects onto the canvas. Ensure the image files exist and are accessible. ```csharp // Load and draw PDF image PdfImage pdfImage = PdfImage.FromFile("photo.jpg"); page.Canvas.DrawImage(pdfImage, 10, 10, 200, 150); // Draw .NET Image object Bitmap bitmap = new Bitmap("icon.png"); page.Canvas.DrawImage(bitmap, new RectangleF(10, 200, 50, 50)); ``` -------------------------------- ### PdfLinearGradientBrush Examples Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Illustrates creating and using PdfLinearGradientBrush for gradient fills in rectangles, including horizontal gradients. ```APIDOC ## PdfLinearGradientBrush Examples ### Description Examples of creating and using linear gradient brushes. ### Code Examples **Gradient from blue to white:** ```csharp // Gradient from blue to white PdfLinearGradientBrush gradientBrush = new PdfLinearGradientBrush( new PointF(10, 10), new PointF(200, 200), Color.Blue, Color.White); page.Canvas.DrawRectangle(gradientBrush, new RectangleF(10, 10, 190, 190)); ``` **Horizontal gradient:** ```csharp RectangleF bounds = new RectangleF(10, 10, 200, 100); PdfLinearGradientBrush hGradient = new PdfLinearGradientBrush(bounds, 0, Color.Red, Color.Yellow); page.Canvas.DrawRectangle(hGradient, bounds); ``` ``` -------------------------------- ### Create PdfRadioButtonFields Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfFormFields.md Example of creating two radio buttons with the same name for mutual exclusivity, and setting one as checked. ```csharp PdfRadioButtonField radio1 = new PdfRadioButtonField(doc.Pages[0], "gender"); radio1.Bounds = new RectangleF(100, 600, 15, 15); PdfRadioButtonField radio2 = new PdfRadioButtonField(doc.Pages[0], "gender"); radio2.Bounds = new RectangleF(200, 600, 15, 15); radio2.Checked = true; doc.Form.Fields.Add(radio1); doc.Form.Fields.Add(radio2); ``` -------------------------------- ### Scale and Draw Image Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfImage.md Demonstrates how to scale an image before drawing it onto a PDF page. This example calculates new dimensions to be 75% of the original size and centers the image horizontally. ```csharp PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); PdfImage image = PdfImage.FromFile("chart.png"); // Calculate scaled dimensions (75% of original) float width = image.Width * 0.75f; float height = image.Height * 0.75f; // Center image horizontally on page float x = (page.Canvas.ClientSize.Width - width) / 2; page.Canvas.DrawImage(image, x, 60, width, height); doc.SaveToFile("output.pdf"); ``` -------------------------------- ### Convert PDF to OFD Format (C#) Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example illustrates how to load a PDF document and save it to the OFD (Open Fixed-layout Document) format. ```csharp // Create pdf document PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile(input); // Convert pdf to ofd pdf.SaveToFile(output, FileFormat.OFD); ``` -------------------------------- ### DrawRectangle Examples Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfCanvas.md Shows how to draw rectangles with different styles: filled, outlined, or both. Requires a PdfPageBase object and appropriate brush and pen settings. ```csharp // Filled rectangle page.Canvas.DrawRectangle(new PdfSolidBrush(Color.LightBlue), new RectangleF(10, 10, 100, 50)); // Outlined rectangle page.Canvas.DrawRectangle(new PdfPen(Color.Black, 2), new RectangleF(10, 70, 100, 50)); // Filled with border page.Canvas.DrawRectangle( new PdfPen(Color.Black, 1), new PdfSolidBrush(Color.Yellow), new RectangleF(10, 130, 100, 50)); ``` -------------------------------- ### Create PDF Table with Custom Borders Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates how to apply custom borders to a PDF table and its cells. It utilizes the BeginRowLayout event to style individual cell borders. ```csharp PdfTable table = new PdfTable(); PdfTableStyle style = new PdfTableStyle(); style.CellPadding = 2; style.BorderPen = new PdfPen(Color.Gray, 1f); table.Style = style; table.BeginRowLayout += new BeginRowLayoutEventHandler(table_BeginRowLayout); table.Draw(page, new PointF(60, 320)); private void table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args) { PdfCellStyle cellStyle = new PdfCellStyle(); cellStyle.BorderPen = new PdfPen(Color.LightBlue, 0.9f); args.CellStyle = cellStyle; } ``` -------------------------------- ### Convert Encrypted PDF to PDF/A (C#) Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates converting an encrypted PDF file to the PDF/A-2A standard, providing the password for decryption during the process. ```csharp // Create a new PdfStandardsConverter object with the input file path and password PdfStandardsConverter converter = new PdfStandardsConverter(@"..\..\..\..\..\..\Data\Decryption.pdf", "test"); // Convert the input PDF to PDF/A-2A standard and save it converter.ToPdfA2A("EncryptedPDFToPDFA.pdf"); ``` -------------------------------- ### Configure Multi-Page PDF Printing Layout and Range Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example shows how to configure multi-page printing layouts, select a specific page range, set paper margins, and define orientation. It then prints the document. ```csharp //Create a pdf document PdfDocument doc = new PdfDocument(); //Select muti page to one paper layout doc.PrintSettings.SelectMultiPageLayout(2, 2, false, PdfMultiPageOrder.Horizontal); //Set print page range doc.PrintSettings.SelectPageRange(3, 15); //Set paper margins,measured in hundredths of an inch doc.PrintSettings.SetPaperMargins(10, 10, 10, 10); //Indicating whether the page is printed in landscape or portrait orientation. doc.PrintSettings.Landscape = false; //Print document doc.Print(); //Close the document doc.Close(); ``` -------------------------------- ### Split PDF Document into Multiple Files Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates how to split a PDF document into multiple files based on a specified naming pattern. Each page or a range of pages can be saved as a separate PDF. ```csharp // Open PDF document PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"..\..\..\..\..\..\Data\SplitDocument.pdf"); // Split the document based on the specified pattern String pattern = "SplitDocument-{0}.pdf"; doc.Split(pattern); String lastPageFileName = String.Format(pattern, doc.Pages.Count - 1); doc.Close(); ``` -------------------------------- ### Create PDF with Transparency Effects and Blend Modes Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Generates a PDF document with images drawn using various transparency levels and blend modes. This example iterates through all available PdfBlendMode options. ```csharp // Create a pdf document PdfDocument doc = new PdfDocument(); PdfSection section = doc.Sections.Add(); // Iterate through each blend mode foreach (PdfBlendMode mode in Enum.GetValues(typeof(PdfBlendMode))) { // Add a page PdfPageBase page = section.Pages.Add(); // Draw base image page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight); page.Canvas.Save(); // Draw images with varying transparency for (int i = 0; i < 5; i++) { float alpha = 1.0f / 6 * (5 - i); // Set transparency for page page.Canvas.SetTransparency(alpha, alpha, mode); // Draw image with transparency page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight); } page.Canvas.Restore(); } ``` -------------------------------- ### Create PDF Portfolio with Files and Subfolders Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates how to create a PDF document and add files to its collection, including the creation of subfolders. The document is then saved and disposed of. Ensure 'targetFile' and 'files' are properly defined before execution. ```csharp // Create a PDF document PdfDocument doc = new PdfDocument(targetFile); // Iterate through the files and add each file to the document's collection for (int i = 0; i < files.Length; i++) { doc.Collection.Folders.AddFile(files[i]); // Create a subfolder PdfFolder folder = doc.Collection.Folders.CreateSubfolder("SubFolder" + (i + 1)); // Add the current file to the subfolder folder.AddFile(files[i]); } // Save the document doc.SaveToFile(result); // Dispose of the document doc.Dispose(); ``` -------------------------------- ### Retrieve Coordinates of a Text Box Field Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example shows how to get the location of a specific text box field within a PDF form. Ensure 'TextBoxSampleB.pdf' exists and contains a text field named 'Text1'. ```csharp //Create a pdf document PdfDocument doc = new PdfDocument(); //Load from file doc.LoadFromFile("TextBoxSampleB.pdf"); //Get form fields PdfFormWidget formWidget = doc.Form as PdfFormWidget; //Get textbox PdfTextBoxFieldWidget textbox = formWidget.FieldsWidget["Text1"] as PdfTextBoxFieldWidget; //Get the location of the textbox PointF location = textbox.Location; ``` -------------------------------- ### Create a Simple PDF Document Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Demonstrates how to create a new PDF document and add a page with "Hello, World!" text. ```csharp //Create a pdf instance PdfDocument doc = new PdfDocument(); //Create one page PdfPageBase page = doc.Pages.Add(); //Draw the text page.Canvas.DrawString("Hello, World!", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10); ``` -------------------------------- ### PdfRadialGradientBrush Example Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Demonstrates creating and using PdfRadialGradientBrush for radial gradient fills in ellipses. ```APIDOC ## PdfRadialGradientBrush Example ### Description Example of creating and using a radial gradient brush. ### Code Example ```csharp PdfRadialGradientBrush radialBrush = new PdfRadialGradientBrush( new PointF(100, 100), 80, Color.Yellow, Color.Orange); page.Canvas.DrawEllipse(radialBrush, new RectangleF(20, 20, 160, 160)); ``` ``` -------------------------------- ### Set Up PDF Pages with Different Sizes, Orientations, and Margins Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Demonstrates configuring PDF pages with various sizes (A4, A3), orientations (Landscape), rotations (90, 180 degrees), and custom margins. It also shows adding pages to sections. ```csharp // Create a pdf document PdfDocument doc = new PdfDocument(); // Set the margin PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; // Create one page with A4 size and specified margin PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin); page.BackgroundColor = Color.Chocolate; // Add another page with A4 size and specified margin page = doc.Pages.Add(PdfPageSize.A4, margin); page.BackgroundColor = Color.Coral; // Add a page with A3 size, rotated 180 degrees, and landscape orientation page = doc.Pages.Add(PdfPageSize.A3, margin, PdfPageRotateAngle.RotateAngle180, PdfPageOrientation.Landscape); page.BackgroundColor = Color.LightPink; // Create a section and add a page to it PdfSection section = doc.Sections.Add(); page = section.Pages.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = margin; // Set background color for the page page = section.Pages.Add(); page.BackgroundColor = Color.LightSkyBlue; // Add a landscape-oriented section section = doc.Sections.Add(); section.PageSettings.Orientation = PdfPageOrientation.Landscape; page = section.Pages.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = margin; // Add a section with 90-degree rotation section = doc.Sections.Add(); page = section.Pages.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = margin; section.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90; // Add a section with 180-degree rotation section = doc.Sections.Add(); page = section.Pages.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = margin; section.PageSettings.Rotate = PdfPageRotateAngle.RotateAngle180; ``` -------------------------------- ### Create PDF Booklet with Binding Options Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Demonstrates how to set binding options, such as left binding, and specify the size for creating a PDF booklet. ```csharp // Create a PDF document PdfDocument doc = new PdfDocument(); // Set the binding mode for the booklet. BookletOptions bookletOptions = new BookletOptions(); bookletOptions.BookletBinding = PdfBookletBindingMode.Left; // Set the size for the booklet. float width = PdfPageSize.A4.Width * 2; float height = PdfPageSize.A4.Height; SizeF size = new SizeF(width, height); // Generate the booklet file by creating a booklet with the specified options PdfBookletCreator.CreateBooklet(doc, outputstream, size, bookletOptions); ``` -------------------------------- ### Create PDF Document with Templates Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Initializes a PDF document, sets viewer preferences, defines margins, and configures document and section templates. This is used to set up the basic structure and appearance of the PDF. ```csharp //Create a pdf document PdfDocument doc = new PdfDocument(); doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft; //Set the margin PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; SetDocumentTemplate(doc, PdfPageSize.A4, margin); //Create one section PdfSection section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins = new PdfMargins(0); SetSectionTemplate(section, PdfPageSize.A4, margin, "Section 1"); //Create one page PdfNewPage page = section.Pages.Add(); ``` -------------------------------- ### Install Spire.PDF NuGet Package Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/README.md Use the dotnet CLI to add the Spire.PDF package to your project. ```bash dotnet add package Spire.PDF ``` -------------------------------- ### Configuration Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/INDEX.md Overview of configuration options for Spire.PDF, including document settings, page setup, and security. ```APIDOC ## Configuration ### Description Details on various configuration settings available for customizing PDF document generation and behavior. ### Key Configuration Areas - **Document Configuration**: Metadata, versioning, incremental updates. - **Page Settings**: Page size, margins. - **HTML Conversion**: Options for converting HTML to PDF. - **Compression**: Settings for compressing document content. - **Form Fields**: Configuration for interactive form fields. - **Security and Encryption**: Password protection and encryption settings. - **XMP Metadata**: Setup for embedding XMP metadata. - **Booklet Configuration**: Settings for booklet printing. - **Layer Configuration**: Management of optional content layers. ### Related Documentation - [configuration.md](configuration.md) ``` -------------------------------- ### Demonstrate Text Drawing Techniques Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Initializes a PDF document and calls various methods to demonstrate different text drawing functionalities. ```csharp // Create a pdf instance PdfDocument doc = new PdfDocument(); // Create one page PdfPageBase page = doc.Pages.Add(); // Draw the text - brush DrawText(page); // Draw the text - alignment AlignText(page); // Draw the text - align in rectangle AlignTextInRectangle(page); // Draw the text - transform TransformText(page); RotateText(page); // Draw the text - alignment private void AlignText(PdfPageBase page) { PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f); PdfSolidBrush brush = new PdfSolidBrush(Color.Blue); // Draws left-aligned text PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); page.Canvas.DrawString("Left!", font, brush, 0, 20, leftAlignment); page.Canvas.DrawString("Left!", font, brush, 0, 50, leftAlignment); // Draws right-aligned text PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 20, rightAlignment); page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 50, rightAlignment); // Draws center-aligned text PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, page.Canvas.ClientSize.Width / 2, 40, centerAlignment); } // Draw the text - align in rectangle private void AlignTextInRectangle(PdfPageBase page) { // Create the font to use and set the font style PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f); PdfSolidBrush brush = new PdfSolidBrush(Color.Blue); RectangleF rctg1 = new RectangleF(0, 70, page.Canvas.ClientSize.Width / 2, 100); RectangleF rctg2 = new RectangleF(page.Canvas.ClientSize.Width / 2, 70, page.Canvas.ClientSize.Width / 2, 100); // Draw rectangle and specifies its fill color and position page.Canvas.DrawRectangle(new PdfSolidBrush(Color.LightBlue), rctg1); page.Canvas.DrawRectangle(new PdfSolidBrush(Color.LightSkyBlue), rctg2); // Draws left-aligned text PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top); page.Canvas.DrawString("Left! Left!", font, brush, rctg1, leftAlignment); page.Canvas.DrawString("Left! Left!", font, brush, rctg2, leftAlignment); // Draws right-aligned text PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); page.Canvas.DrawString("Right! Right!", font, brush, rctg1, rightAlignment); page.Canvas.DrawString("Right! Right!", font, brush, rctg2, rightAlignment); // Draws center-aligned text PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Bottom); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg1, centerAlignment); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg2, centerAlignment); } private void RotateText(PdfPageBase page) { // Save graphics state PdfGraphicsState state = page.Canvas.Save(); // Draw the text - transform PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f); PdfSolidBrush brush = new PdfSolidBrush(Color.Blue); PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); float x = page.Canvas.ClientSize.Width / 2; float y = 380; page.Canvas.TranslateTransform(x, y); for (int i = 0; i < 12; i++) { // Rotate Canvas page.Canvas.RotateTransform(30); // Draw text page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, 20, 0, centerAlignment); } // Restore graphics page.Canvas.Restore(state); } private void TransformText(PdfPageBase page) { // Save graphics state PdfGraphicsState state = page.Canvas.Save(); // Draw the text - transform PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f); PdfSolidBrush brush1 = new PdfSolidBrush(Color.DeepSkyBlue); PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue); page.Canvas.TranslateTransform(20, 200); page.Canvas.ScaleTransform(1f, 0.6f); page.Canvas.SkewTransform(-10, 0); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush1, 0, 0); page.Canvas.SkewTransform(10, 0); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, 0); page.Canvas.ScaleTransform(1f, -1f); page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush2, 0, -2 * 18); // Restore graphics page.Canvas.Restore(state); } private void DrawText(PdfPageBase page) { ``` -------------------------------- ### Create a Simple PDF Document Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/README.md Demonstrates how to create a new PDF document, add a page, draw text, and save the document to a file. Requires PdfDocument, PdfCanvas, and PdfFont classes. ```csharp using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; // Create new document PdfDocument doc = new PdfDocument(); // Add a page PdfPageBase page = doc.Pages.Add(); // Draw text page.Canvas.DrawString("Hello, World!", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10); // Save to file doc.SaveToFile("output.pdf"); doc.Close(); ``` -------------------------------- ### PdfPen Constructors and Usage Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Demonstrates how to create and use PdfPen objects with different configurations for drawing lines and shapes. ```APIDOC ## PdfPen Represents a pen for drawing lines and outlines. Defines stroke color, width, and style. ### Constructor ```csharp public PdfPen(Color color) public PdfPen(Color color, float width) public PdfPen(PdfBrush brush) public PdfPen(PdfBrush brush, float width) ``` Creates a pen for drawing lines and shape outlines. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `color` | Color | Yes | — | Line color. | | `width` | float | No | 1.0f | Line width in points. | | `brush` | PdfBrush | Yes | — | Brush for line fill (allows gradients). | **Returns:** A new `PdfPen` instance ### Properties | Property | Type | Description | |----------|------|-------------| | `Color` | `Color` | Line color. | | `Width` | `float` | Line width in points. | | `DashStyle` | `PdfDashStyle` | Line pattern: `Solid`, `Dash`, `Dot`, `DashDot`, etc. | | `LineJoin` | `PdfLineJoin` | Corner style: `Bevel`, `Miter`, `Round`. | | `StartCap` | `PdfLineCap` | Start endpoint style: `Butt`, `Round`, `Square`. | | `EndCap` | `PdfLineCap` | End endpoint style. | ### Examples **Simple solid line:** ```csharp PdfPen pen = new PdfPen(Color.Black, 2); page.Canvas.DrawLine(pen, new PointF(0, 0), new PointF(200, 200)); ``` **Rectangle outline:** ```csharp PdfPen borderPen = new PdfPen(Color.Red, 1.5f); page.Canvas.DrawRectangle(borderPen, new RectangleF(10, 10, 100, 50)); ``` **Dashed line:** ```csharp PdfPen dashedPen = new PdfPen(Color.Blue, 1); dashedPen.DashStyle = PdfDashStyle.Dash; page.Canvas.DrawLine(dashedPen, new PointF(0, 0), new PointF(200, 0)); ``` **Dotted line:** ```csharp PdfPen dottedPen = new PdfPen(Color.Green, 1); dottedPen.DashStyle = PdfDashStyle.Dot; page.Canvas.DrawLine(dottedPen, new PointF(0, 50), new PointF(200, 50)); ``` **Thick line with rounded corners:** ```csharp PdfPen roundPen = new PdfPen(Color.Purple, 5); roundPen.LineJoin = PdfLineJoin.Round; roundPen.StartCap = PdfLineCap.Round; roundPen.EndCap = PdfLineCap.Round; page.Canvas.DrawLine(roundPen, new PointF(0, 100), new PointF(200, 100)); ``` ``` -------------------------------- ### Create Texture Brush from Image Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Demonstrates how to create a PdfTextureBrush using an image file to fill a rectangle with a repeating pattern. Ensure the image file exists and is accessible. ```csharp PdfImage textureImage = PdfImage.FromFile("pattern.png"); PdfTextureBrush textureBrush = new PdfTextureBrush(textureImage); // Fill rectangle with texture page.Canvas.DrawRectangle(textureBrush, new RectangleF(10, 10, 200, 150)); ``` -------------------------------- ### PdfDocument Constructor Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfDocument.md Creates a new, empty PDF document instance. This is the starting point for generating new PDF files. ```APIDOC ## PdfDocument() ### Description Creates a new, empty PDF document. ### Method Constructor ### Parameters None ### Response A new `PdfDocument` instance. ### Example ```csharp PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); page.Canvas.DrawString("Hello, World!", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10); doc.SaveToFile("output.pdf"); ``` ``` -------------------------------- ### PdfLineAnnotation Constructor Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfAnnotations.md Creates a line annotation with optional arrows and labels, defined by its bounds, start point, and end point. ```APIDOC ## PdfLineAnnotation Constructor ### Description Creates a line annotation. ### Method `PdfLineAnnotation(RectangleF bounds, PointF startPoint, PointF endPoint)` ### Parameters #### Path Parameters - **bounds** (RectangleF) - Required - Bounding rectangle of the annotation. - **startPoint** (PointF) - Required - Starting point of the line. - **endPoint** (PointF) - Required - Ending point of the line. ``` -------------------------------- ### Create Digital Signature with Custom PKCS7 Formatter Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates creating a digital signature using a custom PKCS7 formatter with a provided certificate. It configures signature properties similar to a standard signature but utilizes a custom formatter for advanced scenarios. ```csharp // Load a certificate for digital signature X509Certificate2 cert = new X509Certificate2(certificatePath, password); // Create a custom PKCS7 signature formatter using the certificate CustomPKCS7SignatureFormatter customPKCS7SignatureFormatter = new CustomPKCS7SignatureFormatter(cert); // Create a PdfSignature object with the document, the first page of the document, the custom signature formatter, and an identifier PdfSignature signature = new PdfSignature(doc, doc.Pages[0], customPKCS7SignatureFormatter, "signature0"); signature.Bounds = new RectangleF(new PointF(90, 550), new SizeF(270, 90)); signature.GraphicsMode = GraphicMode.SignDetail; signature.NameLabel = "Signer:"; signature.Name = "Test"; signature.Reason = "The certificate of this document"; signature.DistinguishedNameLabel = "DN: "; signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill | PdfCertificationFlags.ForbidChanges; // Set the font for sign details and sign name PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 15f)); signature.SignDetailsFont = font; signature.SignNameFont = font; signature.SignImageLayout = SignImageLayout.None; ``` -------------------------------- ### Create a Simple PDF Table Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This snippet illustrates how to create a basic PDF table with a header and populate it with data. Use this for displaying lists of information like country data. ```csharp PdfBrush brush1 = PdfBrushes.Black; PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold)); PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center); page.Canvas.DrawString("Country List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1); y = y + font1.MeasureString("Country List", format1).Height; y = y + 5; PdfTable table = new PdfTable(); table.Style.CellPadding = 2; table.Style.HeaderSource = PdfHeaderSource.Rows; table.Style.HeaderRowCount = 1; table.Style.ShowHeader = true; table.DataSource = dataSource; PdfLayoutResult result = table.Draw(page, new PointF(60, y)); y = y + result.Bounds.Height + 5; PdfBrush brush2 = PdfBrushes.Gray; PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 9f)); page.Canvas.DrawString(String.Format("* {0} countries in the list.", data.Length - 1), font2, brush2, 65, y); ``` -------------------------------- ### XMP Metadata Operations Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/AdvancedFeatures.md Demonstrates how to set and get string properties for XMP metadata, including standard and custom namespaces. ```APIDOC ## PdfXmpMetadata ### Description Provides methods for managing XMP metadata within PDF documents. ### Methods #### SetPropertyString ```csharp public void SetPropertyString(string namespaceName, string propertyName, string value) ``` Sets a string property in the XMP metadata. #### GetPropertyString ```csharp public string GetPropertyString(string namespaceName, string propertyName) ``` Retrieves a string property from the XMP metadata. ### Example: Standard Metadata ```csharp PdfDocument doc = new PdfDocument(); doc.LoadFromFile("document.pdf"); // Set standard Dublin Core metadata doc.Metadata.SetPropertyString( "http://purl.org/dc/elements/1.1/", "creator", "John Doe"); doc.Metadata.SetPropertyString( "http://purl.org/dc/elements/1.1/", "description", "Sample PDF document"); doc.SaveToFile("output.pdf"); ``` ### Example: Custom Namespace Metadata ```csharp PdfDocument doc = new PdfDocument(); doc.LoadFromFile("document.pdf"); // Register custom namespace PdfXmpNamespace.RegisterNamespace("http://example.com/custom", "custom"); // Set custom properties doc.Metadata.SetPropertyString( "http://example.com/custom", "department", "Engineering"); doc.Metadata.SetPropertyString( "http://example.com/custom", "project", "Project Alpha"); // Clean up PdfXmpNamespace.ResetNamespaces(); doc.SaveToFile("output.pdf"); ``` ``` -------------------------------- ### PdfLineCap Enum Definition Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/api-reference/PdfBrushAndPen.md Defines the styles for the start and end points of lines drawn with PdfPen, including Butt, Round, and Square. ```csharp public enum PdfLineCap { Butt, Round, Square } ``` -------------------------------- ### Create PDF Action Chain in C# Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md This example demonstrates how to create a sequence of actions in a PDF document. It defines JavaScript alerts and a goto action to navigate to the last page, linking them together using the 'NextAction' property. ```csharp // Create a PDF document PdfDocument doc = new PdfDocument(); // Draw pages and get the last page PdfPageBase lastPage = DrawPages(doc); // Define JavaScript action for after the document is opened String script = "app.alert({" + " cMsg: \"I'll lead; you must follow me.\"," + " nIcon: 3," + " cTitle: \"JavaScript Action\"" + "});"; PdfJavaScriptAction action1 = new PdfJavaScriptAction(script); doc.AfterOpenAction = action1; // Define JavaScript action for the next action after action1 script = "app.alert({" + " cMsg: \"The first page!\"," + " nIcon: 3," + " cTitle: \"JavaScript Action\"" + "});"; PdfJavaScriptAction action2 = new PdfJavaScriptAction(script); action1.NextAction = action2; // Define a destination to navigate to the last page PdfDestination dest = new PdfDestination(lastPage); dest.Zoom = 1; PdfGoToAction action3 = new PdfGoToAction(dest); action2.NextAction = action3; // Define JavaScript action for the next action after action3 script = "app.alert({" + " cMsg: \"Oh sorry, it's the last page. I'm missing!\"," + " nIcon: 3," + " cTitle: \"JavaScript Action\"" + "});"; PdfJavaScriptAction action4 = new PdfJavaScriptAction(script); action3.NextAction = action4; // Save the PDF file doc.SaveToFile("ActionChain.pdf"); doc.Close(); ``` -------------------------------- ### Create PDF Document with Pagination and Headers/Footers Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Initializes a PDF document, sets margins, and adds sections for cover and content. It demonstrates how to draw custom content, headers, footers, and page numbers on different sections of the PDF. ```csharp // Create a new instance of a PDF document PdfDocument doc = new PdfDocument(); // Set the margin for the document PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); PdfMargins margin = new PdfMargins(); margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Bottom = margin.Top; margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point); margin.Right = margin.Left; // Draw the cover page using specified margin and add it to the document DrawCover(doc, doc.Sections.Add(), margin); // Draw the content page using specified margin and add it to the document DrawContent(doc, doc.Sections.Add(), margin); // Draw the page number on the second section of the document using specified margin, // starting from page 1 and counting the total number of pages in the second section DrawPageNumber(doc.Sections[1], margin, 1, doc.Sections[1].Pages.Count); private void DrawCover(PdfDocument pdf, PdfSection section, PdfMargins margin) { // Set the page size of the section to A4 section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Margins.All = 0; // Add a new page to the section PdfPageBase page = section.Pages.Add(); // Create a new instance of PdfPageLabels for the document pdf.PageLabels = new PdfPageLabels(); // Add page labels to the document starting from index 0 with lowercase Roman numerals and prefix "cover " pdf.PageLabels.AddRange(0, PdfPageLabels.Lowercase_Roman_Numerals_Style, "cover "); // Call a method to draw the header and footer on the page DrawPageHeaderAndFooter(page, margin, true); // Set up colors, fonts, and text format for the content PdfBrush brush1 = PdfBrushes.LightGray; PdfBrush brush2 = PdfBrushes.Blue; PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 8f)); PdfStringFormat format = new PdfStringFormat(); format.MeasureTrailingSpaces = true; String text1 = "(All text and picture from "; String text2 = "Wikipedia"; String text3 = ", the free encyclopedia)"; float x = 0, y = 10; // Adjust the starting position of drawing based on the margin x = x + margin.Left; y = y + margin.Top; // Draw the content strings on the page page.Canvas.DrawString(text1, font1, brush1, x, y, format); x = x + font1.MeasureString(text1, format).Width; page.Canvas.DrawString(text2, font1, brush2, x, y, format); x = x + font1.MeasureString(text2, format).Width; page.Canvas.DrawString(text3, font1, brush1, x, y, format); // Set up colors, image, and other parameters for the cover PdfBrush brush3 = PdfBrushes.Black; PdfBrush brush4 = new PdfSolidBrush(new PdfRGBColor(0xf9, 0xf9, 0xf9)); PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SciencePersonificationBoston.jpg"); String text = "Personification of \"Science\" in front of the Boston Public Library"; float r = image.PhysicalDimension.Height / image.Height; PdfPen pen = new PdfPen(brush1, r); SizeF size = font1.MeasureString(text, image.PhysicalDimension.Width - 2); PdfTemplate template = new PdfTemplate(image.PhysicalDimension.Width + 4 * r + 4, image.PhysicalDimension.Height + 4 * r + 7 + size.Height); // Draw a rectangle with border and fill on the template template.Graphics.DrawRectangle(pen, brush4, 0, 0, template.Width, template.Height); // Adjust the starting position of drawing based on the margin and radius x = y = r + 2; // Draw a rectangle on the template with a brush template.Graphics.DrawRectangle(brush1, x, y, image.PhysicalDimension.Width + 2 * r, image.PhysicalDimension.Height + 2 * r); // Adjust the starting position of drawing within the rectangle x = y = x + r; // Draw the image on the template template.Graphics.DrawImage(image, x, y); // Adjust the starting position of drawing for the text below the image x = x - 1; y = y + image.PhysicalDimension.Height + r + 2; // Draw the text on the template using specified font, brush, and rectangle template.Graphics.DrawString(text, font1, brush3, new RectangleF(new PointF(x, y), size)); // Calculate the positioning of the template and draw it on the page canvas float x1 = (page.Canvas.ClientSize.Width - template.Width) / 2; float y1 = (page.Canvas.ClientSize.Height - margin.Top - margin.Bottom) * (1 - 0.618f) - template.Height / 2 + margin.Top; template.Draw(page.Canvas, x1, y1); // Set up alignment and font for the title text format.Alignment = PdfTextAlignment.Center; PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 24f, FontStyle.Bold)); ``` -------------------------------- ### Load PDF from HTML Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/_autodocs/INDEX.md Illustrates how to load and convert HTML content into a PDF document. ```csharp PdfDocument.LoadFromHTML(url, ...) ``` -------------------------------- ### Get Zoom Factor from PDF Document Source: https://github.com/eiceblue/spire.pdf-for-.net/blob/master/CS/pdf_cs.md Retrieves the zoom factor of a PDF document after it's opened. Ensure the PDF has an AfterOpenAction defined. ```csharp // Create a new instance of the PdfDocument class PdfDocument doc = new PdfDocument(); // Load a PDF document from the specified file path doc.LoadFromFile(@"..\..\..\..\..\..\Data\GetZoomFactor.pdf"); // Get the AfterOpenAction of the loaded document as a PdfGoToAction object PdfGoToAction action = doc.AfterOpenAction as PdfGoToAction; // Get the zoom factor value from the destination of the action float zoomvalue = action.Destination.Zoom; // Display a message box showing the zoom factor of the document MessageBox.Show("The zoom factor of the document is " + zoomvalue * 100 + "%."); ```