Thursday, 09 January 2014 02:47

Fill Form Fields in PDF File in C#

We have already demonstrated how to create form fields in PDF file. This article mainly shows you how developers fill form field in PDF in C# only with 3 simple steps by using a standalone .NET PDF component Spire.PDF.

Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll". Here comes to the details of how developers Fill Form Fields by using Spire.PDF:

Step 1: Open the form that needs to fill the data

[C#]
//Create a pdf document
PdfDocument doc = new PdfDocument();
//Load from file
doc.LoadFromFile(@"..\..\FormField.pdf");

Step 2: Update the data to the form

[C#]
//Get form
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;


//Fill the data for textBoxField
if (field is PdfTextBoxFieldWidget)
   {
    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
    switch (textBoxField.Name)
     {

     case "email":
        textBoxField.Text = "support@e-iceblue.com";
    break;
     case "password":
        textBoxField.Password = true;
        textBoxField.Text = "e-iceblue";

//Fill the data for listBoxField
if (field is PdfListBoxWidgetFieldWidget)
  {
     PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget;
     switch (listBoxField.Name)
       {

        case "email_format":
         int[] index = { 1 };
         listBoxField.SelectedIndex = index;
         break;


//Fill the data for comBoxField
if (field is PdfComboBoxWidgetFieldWidget)
  {
   PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget;
   switch (comBoxField.Name)
    {

     case "title":
       int[] items = { 0 };
       comBoxField.SelectedIndex = items;
       break;


//Fill the data for checkBoxField
if (field is PdfCheckBoxWidgetFieldWidget)
  {
   PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
   switch (checkBoxField.Name)
    {

    case "agreement_of_terms":
      checkBoxField.Checked = true;
      break;

Step 3: Save and launch file

[C#]
//Save the document to file in PDF format
doc.SaveToFile(@"../../FormFieldData.pdf.pdf");
//Launch the file
System.Diagnostics.Process.Start(@"../../FormFieldData.pdf.pdf");

Effective Screenshot:

The original PDF with form fields:

before fill form fields

After fill the form fields:

after fill form fields

View the full code as below:

[C#]
static void Filldata()
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\FormField.pdf");
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;
            for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                    switch (textBoxField.Name)
                    {
                        case "email":
                            textBoxField.Text = "support@e-iceblue.com";
                            break;
                        case "username":
                            textBoxField.Text = "E-iceblue";
                            break;
                        case "password":
                            textBoxField.Password = true;
                            textBoxField.Text = "e-iceblue";
                            break;
                        case "password2":
                            textBoxField.Password = true;
                            textBoxField.Text = "e-iceblue";
                            break;
                        case "company_name ":
                            textBoxField.Text = "E-iceblue";
                            break;
                        case "first_name":
                            textBoxField.Text = "James";
                            break;
                        case "last_name":
                            textBoxField.Text = "Chen";
                            break;
                        case "middle_name":
                            textBoxField.Text = "J";
                            break;
                        case "address1":
                            textBoxField.Text = "Chengdu";
                            break;
                        case "address2":
                            textBoxField.Text = "Beijing";
                            break;
                        case "city":
                            textBoxField.Text = "Shanghai";
                            break;
                        case "postal_code":
                            textBoxField.Text = "11111";
                            break;
                        case "state":
                            textBoxField.Text = "Shanghai";
                            break;
                        case "phone":
                            textBoxField.Text = "1234567901";
                            break;
                        case "mobile_phone":
                            textBoxField.Text = "123456789";
                            break;
                        case "fax":
                            textBoxField.Text = "12121212";
                            break;
                    }
                }
                if (field is PdfListBoxWidgetFieldWidget)
                {
                    PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget;
                    switch (listBoxField.Name)
                    {
                        case "email_format":
                            int[] index = { 1 };
                            listBoxField.SelectedIndex = index;
                            break;
                    }
                }

                if (field is PdfComboBoxWidgetFieldWidget)
                {
                    PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget;
                    switch (comBoxField.Name)
                    {
                        case "title":
                            int[] items = { 0 };
                            comBoxField.SelectedIndex = items;
                            break;
                    }
                }

                if (field is PdfRadioButtonListFieldWidget)
                {
                    PdfRadioButtonListFieldWidget radioBtnField = field as PdfRadioButtonListFieldWidget;
                    switch (radioBtnField.Name)
                    {
                        case "country":
                            radioBtnField.SelectedIndex = 1;
                            break;
                    }
                }

                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    switch (checkBoxField.Name)
                    {
                        case "agreement_of_terms":
                            checkBoxField.Checked = true;
                            break;
                    }
                }
                if (field is PdfButtonWidgetFieldWidget)
                {
                    PdfButtonWidgetFieldWidget btnField = field as PdfButtonWidgetFieldWidget;
                    switch (btnField.Name)
                    {
                        case "submit":
                            btnField.Text = "Submit";
                            break;
                    }
                }
            }
            doc.SaveToFile(@"../../FormFieldData.pdf.pdf");
            System.Diagnostics.Process.Start(@"../../FormFieldData.pdf.pdf");
Wednesday, 08 January 2014 09:11

How to Add Action Chain to PDF in C#?

PDF supports actions. And Spire.PDF, a very powerful .NET component enables developers to add action chain to PDF file. Action chain means an action get executed automatically after another one.

In this article, a solution is introduced to add action chain to PDF file.

Step 1: Set the action that gets performed right after PDF document is opened

[C#]
String script
                = "app.alert({"
                + "    cMsg: \"I'll lead; you must follow me.\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
PdfJavaScriptAction action1 = new PdfJavaScriptAction(script);
document.AfterOpenAction = action1;

Spire.PDF provides you a class called PdfJavaScriptAction that executes JavaScript code. Create a PdfJavaScriptAction instance “action1” using JavaScript code. And set the property AfterOpenAction of “document” to action1.

Step 2: Set the action that gets performed after “action1” using the property NextAction

[C#]
script
                = "app.alert({"
                + "    cMsg: \"The firt page!\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
PdfJavaScriptAction action2 = new PdfJavaScriptAction(script);
action1.NextAction = action2;

Step 3: Set the action that gets performed after “action2”

[C#]
PdfDestination dest = new PdfDestination(pagetwo);
dest.Zoom = 1;
PdfGoToAction action3 = new PdfGoToAction(dest);
action2.NextAction = action3;

PdfDestination can mark a specified page or location in PDF. Create a PdfDestination instance “dest” using “pagetwo”. Then create a PdfGoToAction instance “action3” using “dest”.

Step 4: Set the action that gets performed after “action3”

[C#]
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;

Step 5: Save the file

[C#]
document.SaveToFile("result.pdf");

Full code:

[C#]
static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();

            PdfPageBase pageone = document.Pages.Add();
            pageone.Canvas.DrawString("This is Page One.",
                                   new PdfFont(PdfFontFamily.Helvetica, 20f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            PdfPageBase pagetwo = document.Pages.Add();
            pagetwo.Canvas.DrawString("This is Page Two.",
                                   new PdfFont(PdfFontFamily.Helvetica, 20f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);

            String script
                = "app.alert({"
                + "    cMsg: \"I'll lead; you must follow me.\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
            PdfJavaScriptAction action1 = new PdfJavaScriptAction(script);
            document.AfterOpenAction = action1;

            script
                = "app.alert({"
                + "    cMsg: \"The first page!\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
            PdfJavaScriptAction action2 = new PdfJavaScriptAction(script);
            action1.NextAction = action2;

            PdfDestination dest = new PdfDestination(pagetwo);
            dest.Zoom = 1;
            PdfGoToAction action3 = new PdfGoToAction(dest);
            action2.NextAction = 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;

            document.SaveToFile("result.pdf");

            System.Diagnostics.Process.Start("result.pdf");
        }

Screenshot:

add action chain in pdf

add action chain in pdf

Draw text in PDF document is an important part and it is not easy to finish. With the help of Spire.PDF, a PDF component, you can not only draw text in PDF document easily for .NET and WPF, you can do this job easily for Silverlight.

We have introduced how to draw text for PDF .NET and PDF WPF. This article will give clear information of how to draw text with C# code for Silverlight.

Make sure Spire.PDF (or Spire.Office) has been installed correctly. Add Spire.PDF.dll as reference in the downloaded Bin folder though the below path: "..\Spire.PDF\Bin\Silverlight4\ Spire.PDF.dll".

Here comes to the steps:

Step 1: Create a PDF document and a page

[C#]
//create a pdf document
PdfDocument document = new PdfDocument();
//create one page
PdfPageBase page = document.Pages.Add();

Step 2: Draw Text

[C#]
//Draw Text - alignment
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f);
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 255, 0));

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);

PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 30, rightAlignment);
page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 60, rightAlignment);

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
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 0, 255));
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);
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.FromArgb(1, 0, 0, 100)), rctg1);
page.Canvas.DrawRectangle(new PdfSolidBrush(Color.FromArgb(1, 0, 0, 150)), rctg2);

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);

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);

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);

//Draw text - brush
String text = "Go! Turn Around! Go! Go! Go!";
PdfPen pen = PdfPens.DeepSkyBlue;
PdfSolidBrush brush = new PdfSolidBrush(Color.FromArgb(10, 0, 0, 0));
PdfStringFormat format = new PdfStringFormat();
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Italic);
SizeF size = font.MeasureString(text, format);
RectangleF rctg= new RectangleF(page.Canvas.ClientSize.Width / 2 + 10, 180,
size.Width / 3 * 2, size.Height * 2);
page.Canvas.DrawString(text, font, pen, brush, rctg, format);

Step 3: Save the document to stream

[C#]
using (Stream ms = saveFiledialog.OpenFile())
{
    document.SaveToStream(ms);

}

Now check the effective screenshot:

Draw_Text_in_PDF_Document_for_Silverlight.png

When dealing with PDF file format, developers may need this: add a button to PDF; clicking on the button will navigate to specified page or location in PDF file. Spire.PDF, specially designed for developers can meet your need in this.

Playing an action executes the action’s recorded commands in the active document. Spire.PDF provides you an action called PDFGoToAction. PDFGoToAction can navigate to specified page or location in PDF file. Spire.PDF also enables developers to add annotations to PDF file. If the content of an annotation is PDFGoToAction, clicking on the area to display annotation invokes PDFGoToAction. This is how to jump to specified page or location in PDF file.

Step 1: Create a PDFGoToAction instance

[C#]
PDFDestination pageBottomDest = new PDFDestination(pagethree);
pageBottomDest.Location = new PointF(0, 5);
pageBottomDest.Mode = PDFDestinationMode.Location;
pageBottomDest.Zoom = 1f;
PDFGoToAction action = new PDFGoToAction(pageBottomDest);

The PDFDestination instance specifies the page number and the location in the page. In this sample code, "pagethree" is page number and (0, 5) specifies the location in "pagethree".

Step 2: Draw a rectangle. The rectangle specifies the area to display annotation content

[C#]
pageone.Canvas.DrawRectangle(PDFBrushes.DarkGray, buttonBounds);
pageone.Canvas.DrawString("To Last Page", buttonFont, PDFBrushes.CadetBlue, buttonBounds, format2);

Step 3: Create a PDFActionAnnotation instance

[C#]
PDFActionAnnotation annotation = new PDFActionAnnotation(buttonBounds, action);

"buttonBounds" specifies the area to display the content of annotation and "action" is bound to "annotation".

Step 4: Add the PDFActionAnnotation instance "annotation" to PDF file

[C#]
(pageone as PDFNewPage).Annotations.Add(annotation);

Effect screenshot:

Jump to Specified Page or Location in PDF

Jump to Specified Page or Location in PDF

Full code:

[C#]
static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();

            PdfPageBase pageone = document.Pages.Add();
            pageone.Canvas.DrawString("This is Page One.",
                                   new PdfFont(PdfFontFamily.Helvetica, 20f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            PdfPageBase pagetwo = document.Pages.Add();
            pagetwo.Canvas.DrawString("This is Page Two.",
                                   new PdfFont(PdfFontFamily.Helvetica, 20f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            PdfPageBase pagethree = document.Pages.Add();
            pagethree.Canvas.DrawString("This is Page Three.",
                                   new PdfFont(PdfFontFamily.Helvetica, 20f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);

            PdfDestination pageBottomDest = new PdfDestination(pagethree);
            pageBottomDest.Location = new PointF(0, 5);
            pageBottomDest.Mode = PdfDestinationMode.Location;
            pageBottomDest.Zoom = 1f;
            PdfGoToAction action = new PdfGoToAction(pageBottomDest);

            PdfTrueTypeFont buttonFont = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
            float buttonWidth = 70;
            float buttonHeight = buttonFont.Height * 1.5f;
            float x = pageone.Canvas.ClientSize.Width - buttonWidth - 100;
            PdfStringFormat format2 = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            RectangleF buttonBounds = new RectangleF(x, 0, buttonWidth, buttonHeight);
            pageone.Canvas.DrawRectangle(PdfBrushes.DarkGray, buttonBounds);
            pageone.Canvas.DrawString("To Last Page", buttonFont, PdfBrushes.CadetBlue, buttonBounds, format2);

            PdfActionAnnotation annotation
                = new PdfActionAnnotation(buttonBounds, action);
            annotation.Border = new PdfAnnotationBorder(0.75f);
            annotation.Color = Color.LightGray;
            (pageone as PdfNewPage).Annotations.Add(annotation);

            document.SaveToFile("result.pdf");

            System.Diagnostics.Process.Start("result.pdf");
        }
Thursday, 02 January 2014 08:59

How to Unfreeze Excel Panes in C#, VB.NET

Excel Freeze Panes keeps rows and columns visible while the rest of the worksheet scrolls. Likewise, we need to unfreeze Excel panes due to work needs in some cases. This article aims at introducing the solution to unfreeze the Excel top row in c# and VB.NET through a utility Excel .NET library Spire.XLS.

First we need to complete the preparatory work:

  • Download the latest 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.

Here comes to the explanation of the C# code:

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

Workbook workbook = new Workbook();

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

workbook.LoadFromFile("sample.xls");

Step 3: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 4: Unfreeze the top row.

sheet.RemovePanes();

Step 5: Save as the generated file.

workbook.SaveToFile("sample.xls",ExcelVersion.Version97to2003);

Please preview the freeze panes effect screenshot:

Excel freeze panes

And the unfreeze panes effect screenshot:

Excel unfreeze panes

Here is the full code in C# and VB.NET:

[C#]
static void Main(string[] args)
{
 Workbook workbook = new Workbook();
 workbook.LoadFromFile("Sample.xls");
 Worksheet sheet = workbook.Worksheets[0];
 sheet.RemovePanes();
 workbook.SaveToFile("sample.xls",ExcelVersion.Version97to2003);
}
[VB.NET]
Private Shared Sub Main(args As String())
	Dim workbook As New Workbook()
	workbook.LoadFromFile("Sample.xls")
	Dim sheet As Worksheet = workbook.Worksheets(0)
	sheet.RemovePanes()
	workbook.SaveToFile("sample.xls",ExcelVersion.Version97to2003)
End Sub

Bookmark can locate a range. Assuming the content of the range is some html code, how to change the content of the range. Spire.Doc supports bookmarks. And you can use Spire.Doc to fulfill the job.

In this article, a solution will be introduced. Spire.Doc provides you a method:

[C#]
public void ReplaceBookmarkContent(TextBodyPart bodyPart)

Replace the content of bookmark with TextBodyPart bodyPart.

This method cannot handle html code directly. Here is what to do. First load the new html code to document. Then select the newly added data as TextBodyPart. At last, call the method to replace the content of the bookmark.

Step 1: Add bookmarks containing html code.

[C#]
Paragraph p2 = section.AddParagraph();
p2.AppendBookmarkStart("bookmark2");
p2.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
p2.AppendBookmarkEnd("bookmark2");

Step 2: Add new html code to document.

[C#]
Section tempSection = document.AddSection();
String html
= "<p>This Bookmark has been <font color=\"#ff0000\">Edited</font></p>";
tempSection.AddParagraph().AppendHTML(html);

Step 3: Get the new added html as TextBodyPart.

[C#]
ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
ParagraphBase replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
TextBodyPart part = new TextBodyPart(selection);

Step 4: Locate the bookmark "bookmark2" and call the method ReplaceBookmarkContent to replace the content. Then remove the temp section.

[C#]
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
//locate the bookmark
bookmarkNavigator.MoveToBookmark("bookmark2");
//replace the content of bookmark
bookmarkNavigator.ReplaceBookmarkContent(part);
//remove temp section
document.Sections.Remove(tempSection);

Preview the original screenshot:

Edit and replace bookmark with HTML

Preview the effect screenshot:

Edit and replace bookmark with HTML

Here comes to the full code:

[C#]
static void Main(string[] args)
{
 Document document = new Document();
 Section section = document.AddSection();

 //create bookmarks
 Paragraph p1 = section.AddParagraph();
 p1.AppendBookmarkStart("bookmark1");
 p1.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
 p1.AppendBookmarkEnd("bookmark1");

 Paragraph p2 = section.AddParagraph();
 p2.AppendBookmarkStart("bookmark2");
 p2.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
 p2.AppendBookmarkEnd("bookmark2");
 document.SaveToFile("BeforeReplace.doc");

 //create a temp section to contain multiple paragraph.
 Section tempSection = document.AddSection();
 String html
 = "<p>This Bookmark has been <font color=\"#ff0000\">Edited</font></p>";
 tempSection.AddParagraph().AppendHTML(html);  
          
 ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
 ParagraphBase replacementLastItem = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
 TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
 TextBodyPart part = new TextBodyPart(selection);

 BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
 //locate the bookmark
 bookmarkNavigator.MoveToBookmark("bookmark2");
 //replace the content of bookmark
 bookmarkNavigator.ReplaceBookmarkContent(part);
 //remove temp section
 document.Sections.Remove(tempSection);

 document.SaveToFile(@"AfterReplace.doc");
}
Thursday, 26 December 2013 06:55

How to Insert Symbol in Word in C#

Sometimes we need to insert a symbol or special character in the paragraph. The article is introducing the solution to insert a symbol in Word with c# code. We will use Ä and Ë as the symbol examples to complete the process, with the help of a Word .NET API called Spire.Doc.

First we need to complete the preparatory work:

  • Download the latest Spire.Doc and install it on your machine.
  • Add the Spire.Doc.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.Doc as namespace.

Here comes to the explanation of the code.

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

[C#]
Document document = new Document();

Step 2: Add a section.

[C#]
Section section = document.AddSection();

Step 3: Add a paragraph.

[C#]
Paragraph paragraph = section.AddParagraph();

Step 4: Use unicode characters to create symbol Ä.

[C#]
TextRange tr = paragraph.AppendText('\u00c4'.ToString());

In fact, the following step5 and step6 are just the option according to your requirement.

Step 5: Set the color of symbol Ä.

[C#]
tr.CharacterFormat.TextColor = Color.Red;

Step 6: Add symbol Ë.

[C#]
paragraph.AppendText('\u00cb'.ToString());

Step 7: Save to Word file.

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

Here is the full code:

[C#]
static void Main(string[] args)
{
 Document document = new Document();
 Section section = document.AddSection();
 Paragraph paragraph = section.AddParagraph();
 TextRange tr = paragraph.AppendText('\u00c4'.ToString());
 tr.CharacterFormat.TextColor = Color.Red;
 paragraph.AppendText('\u00cb'.ToString());
 document.SaveToFile("sample.docx", FileFormat.Docx);
}

Preview the effect screenshot:

insert symbol in word

Thursday, 26 December 2013 06:29

Create Visible Digital Signature in PDF in C#

Digital Signature is widely used to protect the PDF files and it is so important that we always try our best to improve our Spire.PDF better and better. Besides the previous method of creating digital signature in PDF, Spire.PDF now supports to create visible digital signature in PDF with C# code.

Make sure Spire.PDF for .NET (version 2.9 or above) has been installed correctly. Add Spire.PDF.dll as reference in the downloaded Bin folder through the below path: "...\Spire.PDF\Bin\NET4.0\ Spire.PDF.dll".

Here comes to the C# code snippet of how to create visible digital signature as below:

Step 1: Load a PDF file and load a Certificate

[C#]
PdfDocument doc = new PdfDocument(@"..\..\test.pdf");
PdfCertificate cert = new PdfCertificate(@"..\..\Demo.pfx", "e-iceblue");

Step 2: Create a signature and set the position of it

[C#]
var signature = new PdfSignature(doc, doc.Pages[0], cert, "Requestd1");
signature.Bounds = new RectangleF(new PointF(280, 600), new SizeF(260, 90));

Step 3: Set the property of display the signature

[C#]
signature.IsTag = true;

Step 4: Fill the contents of the signature

[C#]
signature.DigitalSignerLable= "Digitally signed by";
signature.DigitalSigner = "Harry Hu for Test";

signature.DistinguishedName = "DN:";
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "London";

signature.ReasonLabel = "Reason: ";
signature.Reason = "Le document est certifie";

signature.DateLabel = "Date: ";
signature.Date = DateTime.Now;

signature.ContactInfoLabel = "Contact: ";
signature.ContactInfo = "123456789";

signature.Certificated = false;

signature.ConfigGraphicType = ConfiguerGraphicType.Picture;
signature.ConfiguerGraphicPath = "..\\..\\img1.png";

Step 5: Set the document permission of the signature

[C#]
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges;

Step 6: Save the document to file in PDF format

[C#]
doc.SaveToFile("sample.pdf");
System.Diagnostics.Process.Start("sample.pdf");

Now, please check the effective screenshot of the visible digital signature:

Create visible digital signature

Creating digital signature in PDF is widely used to protect PDF files. So you need to get and verify the digital signature when you view some PDF files with digital signature. This article shows you a solution of getting and verifying the digital signature in PDF by using Spire.PDF with C# code.

Make sure Spire.PDF for .NET (version 2.9 or above) has been installed correctly. Add Spire.PDF.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.PDF\Bin\NET4.0\ Spire.PDF.dl".

Here comes to the C# code snippet of how to get and verify digital signature as below:

Load a PDF file with digital signature.

[C#]
string filename = @"..\..\DigitalSignature.pdf";

Get all signatures from the PDF:

[C#]
List<PdfSignature> signatures = new List<PdfSignature>();
using (var doc = new PdfDocument(filename))
{
   var form = (PdfFormWidget)doc.Form;
   for (int i = 0; i < form.FieldsWidget.Count; ++i)
   {
        var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;

        if (field != null && field.Signature != null)
        {
            PdfSignature signature = field.Signature; 
            signatures.Add(signature);
         }
    }
}

Get the first signature:

[C#]
PdfSignature signatureOne = signatures[0];

Verify the signature:

[C#]
try
{
  bool bSignature = signatureOne.VerifySignature();
}
catch (Exception ex)
{
     Console.WriteLine(ex.Message);
     Console.ReadLine();
}

Get the certification of signature:

[C#]
X509Certificate2 certificate = signatureOne.Certificate as X509Certificate2;

Get the date of signature:

[C#]
DateTime date = signatureOne.Date;

Get the date on which the signature starts and ends valid:

[C#]
DateTime validStart = certificate.NotBefore;
DateTime validEnd = certificate.NotAfter;

Get the version of the certificate:

[C#]
int version = certificate.Version;

Get the subject distinguished name from the certificate:

[C#]
string subject = certificate.Subject;

Please check the effective screenshot as below:

PDF Digital Signature

Tuesday, 17 December 2013 08:17

How to Convert HTML to XML in C#, VB.NET

Office OpenXML becomes the technology of choice for delivering structured data on the Web, working hand-in-hand with HTML and fully complementing HTML. Consequently, we need to convert HTML to Office OpenXML at some point at work. This article mainly talks about the conversion process through a professional Word .NET library Spire.Doc.

First we need to complete the preparatory work before the procedure:

  • Download the Spire.Doc and install it on your machine.
  • Add the Spire.Doc.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.Doc as namespace.

The following steps will show you how to do this with ease:

Step 1: Create a Word document.

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

Step 2: Load the HTML file.

[C#]
doc.LoadFromFile("Sample.html");

Step 3: Save the HTML as the XML file.

[C#]
doc.SaveToFile("test.xml", FileFormat.Xml);

Here comes to the full C# and VB.NET code

[C#]
static void Main(string[] args)
{
 Document doc = new Document();
 doc.LoadFromFile("Sample.html");
 doc.SaveToFile("test.xml", FileFormat.Xml);
}
[VB.NET]
Shared Sub Main(ByVal args() As String)
 Dim doc As New Document()
 doc.LoadFromFile("sample.html")
 doc.SaveToFile("test.xml", FileFormat.Xml)
End Sub

Preview of original HTML file.

HTML_effect_screenshot

Preview of generated Office OpenXML file.

XML_effect_screenshot

Page 2 of 22