Tuesday, 09 September 2014 02:17

Convertors

This demo shows you how to convert an Excel document (xls/xlsx) to PDF, HTML, Image file format.
{k2-demo src:$server/Spire.XLS/21_Misc/Convertors.aspx|style:height:189px}
using System;
using Spire.Xls;
using System.Drawing;
using System.Drawing.Imaging;

namespace DemoOnlineCode
{
    class Convertors
    {
        public void demoConvert(String filePath, string format,string resultFileName)
        {
            Workbook book = new Workbook();
            book.LoadFromFile(filePath)  ;
            ConvertFormat(book, format, resultFileName);
        }
        private void ConvertFormat(Workbook workbook, string format, string resultFileName)
        {
            switch (format)
            {
                case "PDF":
                    workbook.SaveToFile(resultFileName + ".pdf", Spire.Xls.FileFormat.PDF);
                    break;
                case "Image":
                    Image[] images = new Image[workbook.Worksheets.Count];
                    for (int i = 0; i < workbook.Worksheets.Count; i++)
                    {
                        images[i] = workbook.SaveAsImage(i, 96, 96);
                    }
                    if (images != null && images.Length > 0)
                    {
                        if (images.Length == 1)
                        {
                            images[0].Save(resultFileName+".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        else
                        {
                            for (int i = 0; i < images.Length; i++)
                            {
                                String fileName = String.Format("{0}-Image-{1}.png", resultFileName, i);
                                images[i].Save(fileName, ImageFormat.Png);
                            }
                        }
                    }
                    break;

                case "HTML":   
                    for (int i = 0; i < workbook.Worksheets.Count; i++)
                    {
                        Worksheet sheet = workbook.Worksheets[i];
                        string htmlPath = string.Format(resultFileName+"-{0}.html", i++);
                        sheet.SaveToHtml(htmlPath);
                    }                  
                    break;
            }
        }
    }
}


Imports Spire.XLS
Imports System.Drawing
Imports System.Drawing.Imaging

Namespace DemoOnlineCode
    Class Convertors
        Public Sub demoConvert(filePath As [String], format As String, resultFileName As String)
            Dim book As New Workbook()
            book.LoadFromFile(filePath)
            ConvertFormat(book, format, resultFileName)
        End Sub
        Private Sub ConvertFormat(workbook As Workbook, format As String, resultFileName As String)
            Select Case format
                Case "PDF"
                    workbook.SaveToPdf(resultFileName & ".pdf", Spire.Xls.FileFormat.PDF)
                    Exit Select

                Case "Image"
                    Dim images As Image() = New Image(workbook.Worksheets.Count - 1) {}
                    For i As Integer = 0 To workbook.Worksheets.Count - 1
                        images(i) = workbook.SaveAsImage(i, 96, 96)
                    Next
                    If images IsNot Nothing AndAlso images.Length > 0 Then
                        If images.Length = 1 Then
                            images(0).Save(resultFileName & ".bmp", System.Drawing.Imaging.ImageFormat.Bmp)
                        Else
                            For i As Integer = 0 To images.Length - 1
                                Dim fileName As [String] = [String].Format("{0}-Image-{1}.png", resultFileName, i)
                                images(i).Save(fileName, ImageFormat.Png)
                            Next
                        End If
                    End If
                    Exit Select

                Case "HTML"
                    For i As Integer = 0 To workbook.Worksheets.Count - 1
                        Dim sheet As Worksheet = workbook.Worksheets(i)
                        Dim htmlPath As String = String.Format(resultFileName & "-{0}.html", System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1))
                        sheet.SaveToHtml(htmlPath)
                    Next
                    Exit Select
            End Select
        End Sub
    End Class
End Namespace



Friday, 21 March 2014 02:30

Live Demo

Welcome to E-iceblue Live Demos!

Live Demo gives you something quite different; taking you through individual pieces of E-iceblue products' functionality. You can use your own documents and get to see the result straight away by alerting the tabs at the top of the page.

If you don't find the function you want, please send request to support@e-iceblue.com, we will check and update our database.

Recently Updated

{latest:5}

Most Viewed

{hot:5}
Thursday, 13 February 2014 08:56

Extract Text from Text Boxes in Word Document

A text box's purpose is to allow the user to input text information to be used by the program. Also the existing text information can be extracted from the text box. The following guide focuses on introducing how to extract text from text box in a Word document in C# via Spire.Doc for .NET.

Firstly, check out the text box information in the word document.

extract text from textbox

Secondly, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Now it comes to the steps of how to extract text from text boxes.

Step 1: Load a word document from the file.

[C#]
Document document = new Document();
document.LoadFromFile(@"..\..\Test.docx");

Step 2: Check whether text box exists in the documents.

[C#]
//Verify whether the document contains a textbox or not
if (document.TextBoxes.Count > 0)

Step 3: Initialize a StreamWriter class for saving text which will be extracted next

[C#]
using (StreamWriter sw = File.CreateText("result.txt"))

Step 4: Extracted the text from text boxes.

[C#]
//Traverse the document
foreach (Section section in document.Sections)
{
 foreach (Paragraph p in section.Paragraphs)
{
foreach (DocumentObject obj in p.ChildObjects)

//Extract text from paragraph in TextBox
if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
{
  sw.Write((objt as Paragraph).Text)
 }
//Extract text from Table in TextBox
if (objt.DocumentObjectType == DocumentObjectType.Table)
 {
  Table table = objt as Table;
  ExtractTextFromTables(table, sw);
}
//Extract text from Table 
static void ExtractTextFromTables(Table table, StreamWriter sw)
{
for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sw.Write(paragraph.Text);
                    }
                }
            }
}

After debugging, the following result will be presented:

extract text from textbox

The full code:

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Fields;
using System.IO;
using Spire.Doc.Documents;
namespace ExtractTextFromTextBoxes
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"..\..\Test.docx");

            //Verify whether the document contains a textbox or not
            if (document.TextBoxes.Count > 0)
            {
                using (StreamWriter sw = File.CreateText("result.txt"))
                {
                    foreach (Section section in document.Sections)
                    {
                        foreach (Paragraph p in section.Paragraphs)
                        {
                            foreach (DocumentObject obj in p.ChildObjects)
                            {
                                if (obj.DocumentObjectType == DocumentObjectType.TextBox)
                                {
                                    TextBox textbox = obj as TextBox;
                                    foreach (DocumentObject objt in textbox.ChildObjects)
                                    {
                                        if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
                                        {
                                            sw.Write((objt as Paragraph).Text);
                                        }

                                        if (objt.DocumentObjectType == DocumentObjectType.Table)
                                        {
                                            Table table = objt as Table;
                                            ExtractTextFromTables(table, sw);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        static void ExtractTextFromTables(Table table, StreamWriter sw)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sw.Write(paragraph.Text);
                    }
                }
            }
        }
    }
}
Thursday, 23 January 2014 06:45

Unhide the Excel Row and Column in C#

You can hide the Excel row or column by using the c# code, but a row or column also becomes hidden when you want to show the full Excel worksheet. You can unhide the Excel row and column by using the c# code. This article aims at introducing the method sheet.ShowRow and sheet.ShowColumn in the Excel .NET component Spire.Xls to show the hidden row and column.

First, let’s preview the hidden row and column.

hide the Excel row and column

Here comes to the steps of the process.

Step 1: Create an instance of Spire.XLS.Workbook.

[C#]
Workbook workbook = new Workbook();

Step 2: Load the existing Excel file that hidden the row and column in the specified path.

[C#]
workbook.LoadFromFile("hide.xlsx");

Step 3: Get the first worksheet of the Excel file.

[C#]
Worksheet sheet = workbook.Worksheets[0];

Step 4: Unhide the hidden row and column.

[C#]
sheet.ShowRow(7);
sheet.ShowColumn(3);

Step 5: Generate the new Excel file.

[C#]
workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);

Now let's preview the effect screenshot.

unhide the Excel row and column

Here is the full code.

[C#]
static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("hide.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            // unhide the hidden row and column of the worksheet.
            sheet.ShowRow(7);
            sheet.ShowColumn(3);
            workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
        }
Wednesday, 22 January 2014 08:51

Add Image Header/Footer in C#

Excel header and footer gives additional information of a spreadsheet. And it can be in text and image. We have already shows you the text header and footer in excel worksheet, this guide focuses on introducing how to insert image header and footer for Excel files in C# by using Spire.XLS for .NET.

Firstly, Download Spire.XLS for .NET (or Spire.Office for .NET) and install it on your system. The Spire.XLS installation is clean, professional and wrapped up in a MSI installer.

Then, adds Spire.XLS.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.XLS\Bin\NET4.0\ Spire.XLS.dll".

Now it comes to the details of how to add image header and footer in C#:

Step 1: Create a new excel document and load from the file.

[C#]
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"..\..\XLS1.xlsx");

Step 2: Get a first worksheet.

[C#]
Worksheet sheet = workbook.Worksheets[0];

Step 3: Load the image and set header and footer style.

[C#]
Image image = Image.FromFile(@"..\..\logo.png");

//Set Header format
sheet.PageSetup.LeftHeaderImage = image;
sheet.PageSetup.LeftHeader = "&G";

//Set Footer format
sheet.PageSetup.CenterFooterImage = image;
sheet.PageSetup.CenterFooter = "&G";

Step 4: Save the document to file.

[C#]
workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);

Effected screenshot:

add image header and footer

The full codes:

[C#]
static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\..\XLS1.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            Image image = Image.FromFile(@"..\..\logo.png");

            sheet.PageSetup.LeftHeaderImage = image;
            sheet.PageSetup.LeftHeader = "&G";

            sheet.PageSetup.CenterFooterImage = image;
            sheet.PageSetup.CenterFooter = "&G";

            workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);
        }
Friday, 17 January 2014 07:03

How to Align Excel Text in C#

Spire.XLS specially designed for programmers enables developers to input, edit and delete the text in Excel file. It also enables developers to align text in Excel.

In this article, a solution is introduced to show how to align text in Excel file. Set the vertical alignment using the property VerticalAlignment. Set the horizontal alignment using the property HorizontalAlignment. And set the rotation degree using the property Rotation.

Step 1: Set the vertical alignment

Set the vertical alignment of "B3" to Top.

[C#]
sheet.Range["B3"].Text = "Top";
sheet.Range["B3"].Style.VerticalAlignment = VerticalAlignType.Top;

Set the vertical alignment of "B4" to Center.

[C#]
sheet.Range["B4"].Text = "Center";
sheet.Range["B4"].Style.VerticalAlignment = VerticalAlignType.Center;

Set the vertical alignment of "B5" to Bottom.

[C#]
sheet.Range["B5"].Text = "Bottom";
sheet.Range["B5"].Style.VerticalAlignment = VerticalAlignType.Bottom;

Step 2: Set the horizontal alignment

Set the horizontal alignment of "B7" to Left.

[C#]
sheet.Range["B7"].Text = "Left";
sheet.Range["B7"].Style.HorizontalAlignment = HorizontalAlignType.Left;

Set the horizontal alignment of "B8" to Center.

[C#]
sheet.Range["B8"].Text = "Center";
sheet.Range["B8"].Style.HorizontalAlignment = HorizontalAlignType.Center;

Set the horizontal alignment of "B9" to Right.

[C#]
sheet.Range["B9"].Text = "Right";
sheet.Range["B9"].Style.HorizontalAlignment = HorizontalAlignType.Right;

Step 3: Set the rotation degree

Set the rotation degree of "B10" to 90(counter-clockwise direction).

[C#]
sheet.Range["B10"].Text = "Rotation 90 degree";
sheet.Range["B10"].Style.Rotation = 90;

Set the rotation degree of "B11" to 45(counter-clockwise direction).

[C#]
sheet.Range["B11"].Text = "Rotation 45 degree";
sheet.Range["B11"].Style.Rotation = 45;

Full code and screenshot:

Align Excel Text

static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];

            sheet.Range["B3"].Text = "Top";
            sheet.Range["B3"].Style.VerticalAlignment = VerticalAlignType.Top;

            sheet.Range["B4"].Text = "Center";
            sheet.Range["B4"].Style.VerticalAlignment = VerticalAlignType.Center;

            sheet.Range["B5"].Text = "Bottom";
            sheet.Range["B5"].Style.VerticalAlignment = VerticalAlignType.Bottom;

            sheet.Range["B7"].Text = "Left";
            sheet.Range["B7"].Style.HorizontalAlignment = HorizontalAlignType.Left;

            sheet.Range["B8"].Text = "Center";
            sheet.Range["B8"].Style.HorizontalAlignment = HorizontalAlignType.Center;

            sheet.Range["B9"].Text = "Right";
            sheet.Range["B9"].Style.HorizontalAlignment = HorizontalAlignType.Right;

            sheet.Range["B10"].Text = "Rotation 90 degree";
            sheet.Range["B10"].Style.Rotation = 90;

            sheet.Range["B11"].Text = "Rotation 45 degree";
            sheet.Range["B11"].Style.Rotation = 45;

            sheet.AllocatedRange.AutoFitColumns();
            sheet.Range["B3:B5"].RowHeight = 20;

            workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003);
        }
Thursday, 16 January 2014 08:50

How to Set Word Paragraph Shading in C#

By shading words or paragraphs in a word document, we can emphasize the message and catch others' eyes easily. This article will show you how to set paragraph shading in C# with the help of Spire.Doc.

Firstly, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then, adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Now it comes to the steps of how to set the background color for text or paragraph.

Step 1: Create a new word document and load from the file.

[C#]
Document document = new Document();
document.LoadFromFile(@"..\..\Sample.docx");

Step 2: Get a paragraph.

[C#]
Paragraph paragaph = document.Sections[0].Paragraphs[0];

Step 3: Shading the paragraph or the selected words.

[C#]
//Set background color for the paragraph
paragaph.Format.BackColor = Color.Yellow;

//Set background color for the selected text of paragraph
paragaph = document.Sections[0].Paragraphs[1];
TextSelection selection= paragaph.Find("Blues",true,false);
TextRange range = selection.GetAsOneRange();
range.CharacterFormat.TextBackgroundColor = Color.Yellow;

Step 4: Save the document to file.

[C#]
document.SaveToFile("sample.docx",FileFormat.Docx);

Effected Screenshot:

Set Word Paragraph Shading

Full codes:

[C#]
static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"..\..\Sample.docx");
            Paragraph paragaph = document.Sections[0].Paragraphs[0];

            //Set background color for the paragraph
            paragaph.Format.BackColor = Color.Yellow;

            //Set background color for the selected text of paragraph
            paragaph = document.Sections[0].Paragraphs[1];
            TextSelection selection= paragaph.Find("Blues",true,false);
            TextRange range = selection.GetAsOneRange();
            range.CharacterFormat.TextBackgroundColor = Color.Yellow;

            document.SaveToFile("sample.docx",FileFormat.Docx);
        }
Wednesday, 15 January 2014 08:08

How to Ungroup Excel Cells in C#

Group the Excel cells is to tie a range of cells together so that they can be collapsed or expanded. But usually, we also need to ungroup the Excel cells. Consequently, the articles aims at introducing how to ungroup Excel cells in C#, through a professional Excel .NET Component Spire.Xls.

Just as its name implies, ungroup Excel cells is to ungroup a range of cells that were previously grouped. Before ungroup Excel cells, we should complete the preparatory work:

  • Download the Spire.XLS and install it on your machine.
  • Add the Spire.XLS.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.XLS as namespace.

Then here comes to the explanation of the code:

Step 1: Create an instance of Spire.XLS.Workbook.

[C#]
Workbook workbook = new Workbook();

Step 2: Load the file base on a specified file path.

[C#]
workbook.LoadFromFile(@"group.xlsx");

Step 3: Get the first worksheet.

[C#]
Worksheet sheet = workbook.Worksheets[0];

Step 4: Ungroup the first 5 row cells.

[C#]
sheet.UngroupByRows(1, 5);

Step 5: Save as the generated file.

[C#]
workbook.SaveToFile(@"result.xlsx", ExcelVersion.Version2010);

Full code:

[C#]
static void Main(string[] args)
{
  Workbook workbook = new Workbook();
  workbook.LoadFromFile(@"group.xlsx");
  Worksheet sheet = workbook.Worksheets[0];
  sheet.UngroupByRows(1, 5);
  workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);
}

Please preview the original group effect screenshot:

group excel cells

And the generated ungroup effect screenshot:

ungroup excel cells

Wednesday, 15 January 2014 02:49

How to Apply PDF Page Transitions in C#

Page transitions display a decorative effect such as a dissolve or wipe when you’re turning pages in a document that is exported to PDF format. Page transitions are especially useful when you create a slideshow in PDF format. And Spire.PDF, a powerful .NET component specially designed for developers enables you to apply page transitions to PDF file.

A solution is introduced here to show how to apply page transitions to PDF using Spire.PDF. Spire.PDF provides you a class called PdfSection. PdfSection has a property called PageSettings. And PageSettings has a property called Transition. You can use this property to apply page transitions.

Step 1: Create a new section.

PdfSection section = doc.Sections.Add();
section.PageSettings.Size = PdfPageSize.A4;

Step 2: Create a new PdfPageTransition instance.

section.PageSettings.Transition = new PdfPageTransition();

Step 3: Set the style of page transition.

section.PageSettings.Transition.Style = PdfTransitionStyle.Fade;

You can assign any value that is defined in PdfTransitionStyle to Style.

Step 4: Set the duration of transition effect in seconds.

section.PageSettings.Transition.Duration = 3;

Step 5: Set the page's display duration.

section.PageSettings.Transition.PageDuration = 2;

Step 6: Add more sections and apply more page transitions.

section = doc.Sections.Add();
section.PageSettings.Size = PdfPageSize.A4;
section.PageSettings.Transition = new PdfPageTransition();
section.PageSettings.Transition.Style = PdfTransitionStyle.Box;
section.PageSettings.Transition.Motion = PdfTransitionMotion.Outward;
section.PageSettings.Transition.Duration = 3;
section.PageSettings.Transition.PageDuration = 2;

You can combine the type of PdfPageTransition with the property Direction and the property Dimension of PdfPageTransition to create new and flexible page transition. For example, in this step, the Style of page transition is PdfTransitionStyle.Box and the Motion of page transition is PdfTransitionMotion.Outward.

At last, save the file.

doc.SaveToFile("result.pdf");

To see page transitions in the PDF, open the PDF file in Full Screen.

pdf page transition

pdf page transition

pdf page transition

Here comes to the full code:

static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();

            PdfSection section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Transition = new PdfPageTransition();
            section.PageSettings.Transition.Style = PdfTransitionStyle.Fade;
            section.PageSettings.Transition.Duration = 3;
            section.PageSettings.Transition.PageDuration = 2;

            PdfNewPage page = section.Pages.Add();
            page.BackgroundColor = Color.Blue;
            page.Canvas.DrawString("This is Page One.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            page = section.Pages.Add();
            page.BackgroundColor = Color.Green;
            page.Canvas.DrawString("This is Page Two.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Transition = new PdfPageTransition();
            section.PageSettings.Transition.Style = PdfTransitionStyle.Box;
            section.PageSettings.Transition.Motion = PdfTransitionMotion.Outward;
            section.PageSettings.Transition.Duration = 3;
            section.PageSettings.Transition.PageDuration = 2;

            page = section.Pages.Add();
            page.BackgroundColor = Color.Orange;
            page.Canvas.DrawString("This is Page Three.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            page = section.Pages.Add();
            page.BackgroundColor = Color.Brown;
            page.Canvas.DrawString("This is Page Four.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Transition = new PdfPageTransition();
            section.PageSettings.Transition.Duration = 3;
            section.PageSettings.Transition.Style = PdfTransitionStyle.Dissolve;
            section.PageSettings.Transition.PageDuration = 2;

            page = section.Pages.Add();
            page.BackgroundColor = Color.Orange;
            page.Canvas.DrawString("This is Page Five.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            page = section.Pages.Add();
            page.BackgroundColor = Color.Navy;
            page.Canvas.DrawString("This is Page Six.",new PdfFont(PdfFontFamily.Helvetica, 20f),new PdfSolidBrush(Color.Black),10, 10);

            doc.SaveToFile("result.pdf");
            doc.Close();
        }
Thursday, 09 January 2014 08:32

How to Add PDF Text Watermark in WPF

Watermark is a recognizable text or image that appears under document text. A watermark is useful in the examination of paper because it can be widely used for trademarks, locations and so on. This article aims at introducing how to add PDF text watermark for WPF through a simple WPF PDF API Spire.PDF for WPF. Also it can implement PDF watermark by image.

First we need to complete the preparatory work:

  • Download the latest Spire.PDF and install it on your machine.
  • Add the Spire.PDF.WPF.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.PDF as namespace.

Here comes to the explanation of the code.

Step 1: Create an instance of Spire.PDF.Document

[C#]
PdfDocument doc = new PdfDocument();

Step 2: Load the file base on a specified file path

[C#]
doc.LoadFromFile(@"..\..\Sample1.pdf");

Step 3: Add the text watermark to the first page

[C#]
PdfPageBase page = doc.Pages[0];
PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width/2, page.Canvas.ClientSize.Height/3));
brush.Graphics.SetTransparency(0.3f);
brush.Graphics.Save();
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
brush.Graphics.RotateTransform(-45);
brush.Graphics.DrawString("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,new PdfStringFormat(PdfTextAlignment.Center));
brush.Graphics.Restore();
brush.Graphics.SetTransparency(1);
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

Step 4: Save the PDF file

[C#]
doc.SaveToFile("TextWaterMark.pdf");

Full code:

[C#]
private void button1_Click(object sender, RoutedEventArgs e)
 {
  PdfDocument doc = new PdfDocument();
  doc.LoadFromFile(@"..\..\Sample1.pdf");
  PdfPageBase page = doc.Pages[0];
  PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width/2, page.Canvas.ClientSize.Height/3));
  brush.Graphics.SetTransparency(0.3f);
  brush.Graphics.Save();
  brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
  brush.Graphics.RotateTransform(-45);
  brush.Graphics.DrawString("Spire.Pdf Demo",new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
  brush.Graphics.Restore();
  brush.Graphics.SetTransparency(1);
  page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
  doc.SaveToFile("TextWaterMark.pdf");          
 }

Effect screenshot:

add pdf text watermark for wpf

Page 1 of 22