Friday, 13 December 2013 06:28

Add Annotation to PDF File in C#

Annotation is an important part of PDF file. Spire.PDF, as a developer friendly .NET PDF component can meet your need of dealing annotations. Using Spire.PDF you can add a new annotation, edit an existing annotation and delete annotations and so on.

In this article, we will introduce you how to add new annotations and edit existing annotations. Spire.PDF provides you a class called PdfTextMarkupAnnotation to represent text annotation. Create text annotation using PdfTextMarkupAnnotation.

[C#]
PdfTextMarkupAnnotation annotation1 = new PdfTextMarkupAnnotation("Administrator", "Demo about Annotation.", text , new PointF(0, 0), font);

Parameters of annotation1:

  • "Administrator": specify the author of text annotation
  • "Demo about Annotation": text of annotation
  • text: font and text used to determine the size of mark shadowing on text
  • new PointF(0, 0): not supported at present
  • font: the font of the text which will be marked

You need to set the location of the mark upon text. Move the mouse on the mark in the result file, annotation will show.

[C#]
annotation1.Location = new PointF(point.X + doc.PageSettings.Margins.Left, point.Y + doc.PageSettings.Margins.Left);

Add annotation1 to the specified page of PDF file.

[C#]
(page as PdfNewPage).Annotations.Add(annotation1);

Edit the text of annotation1.

[C#]
(page as PdfNewPage).Annotations[0].Text = "Annotation Edited:(This is a Demo about Annotation)";

Effect screenshot:

add annotation to pdf

Full code:

[C#]
static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add();
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 13);
            string text = "HelloWorld";
            PointF point = new PointF(200, 100);
            page.Canvas.DrawString(text, font, PdfBrushes.CadetBlue, point);

            PdfTextMarkupAnnotation annotation1 = new PdfTextMarkupAnnotation("Administrator", "Demo about Annotation.", text, new PointF(0, 0), font);
            annotation1.Border = new PdfAnnotationBorder(0.75f);
            annotation1.TextMarkupColor = Color.Green;

            annotation1.Location = new PointF(point.X + doc.PageSettings.Margins.Left, point.Y + doc.PageSettings.Margins.Left);
            (page as PdfNewPage).Annotations.Add(annotation1);

            (page as PdfNewPage).Annotations[0].Text = "Annotation Edited:(Demo about Annotation)";

            doc.SaveToFile("result.pdf");

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

Extracting image from PDF is not a complex operation, but sometimes we need to save the image to new PDF file. So the article describes the simple c# code to extract image from PDF and save it to new PDF file through a professional PDF .NET library Spire.PDF.

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

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

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

Step 1: Create a PDF document.

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"..\..\Sample.pdf");

Step 2: Extract the image from PDF document.

[C#]
doc.ExtractImages();

Step 3: Save image file.

[C#]
image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
PdfImage image2 = PdfImage.FromFile(@"image.png");
PdfDocument doc2=new PdfDocument ();
PdfPageBase page=doc2.Pages.Add();

Step 4: Draw image to new PDF file.

[C#]
float width = image.Width * 0.75f;
float height = image.Height * 0.75f;
float x = (page.Canvas.ClientSize.Width - width) / 2;
page.Canvas.DrawImage(image2,x,60,width,height);
doc2.SaveToFile(@"..\..\Image.pdf");

Here is the whole code:

[C#]
static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\Sample.pdf");
            doc.ExtractImages();
            image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
            PdfImage image2 = PdfImage.FromFile(@"image.png");
            PdfDocument doc2=new PdfDocument ();
            PdfPageBase page=doc2.Pages.Add();
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;
            page.Canvas.DrawImage(image2,x,60,width,height);
            doc2.SaveToFile(@"..\..\Image.pdf");
        }

Here comes to the preview of the effect picture:

extract image from pdf

draw image to new pdf

Thursday, 12 December 2013 06:17

Tutorials

Here you will get a collection of tutorials of our ASP.NET applications created with E-iceblue products. It helps you have brief and clear information of how to use our E-iceblue components easily and conveniently.

Feel free to have a trial from E-iceblue Download Centre.

Recently Updated

{latest:5}

Most Viewed

{hot:5}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the demo you want, please contact support@e-iceblue.com for the free customized demo just for you.
Wednesday, 11 December 2013 03:02

Fill Form Fields in Word Document in C#

We have already demonstrated how to create form field. This article mainly shows you how developers fill form field in word document in C# only with 4 simple steps by using a standalone .NET Word component Spire.Doc.

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

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

[C#]
//Create word document
Document document = new Document(@"..\..\..\Data\UserForm.doc");

Step 2: Load data that will fill the form.

[C#]
//Fill data from XML file
using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml"))
{
    XPathDocument xpathDoc = new XPathDocument(stream);
    XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

Step 3: Use the loaded data to fill the form.

[C#]
//fill data
  foreach (FormField field in document.Sections[0].Body.FormFields)
  {
     String path = String.Format("{0}/text()", field.Name);
     XPathNavigator propertyNode = user.SelectSingleNode(path);
     if (propertyNode != null)
     {
         switch (field.Type)
         {
             case FieldType.FieldFormTextInput:
                  field.Text = propertyNode.Value;
                  break;

             case FieldType.FieldFormDropDown:
                  DropDownFormField combox = field as DropDownFormField;
                  for(int i = 0; i < combox.DropDownItems.Count; i++)
                  {
                      if (combox.DropDownItems[i].Text == propertyNode.Value)
                      {
                         combox.DropDownSelectedIndex = i;
                         break;
                      }
                      if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                      {
                         combox.DropDownSelectedIndex = i;
                      }
                  }
                  break;

             case FieldType.FieldFormCheckBox:
                  if (Convert.ToBoolean(propertyNode.Value))
                  {
                      CheckBoxFormField checkBox = field as CheckBoxFormField;
                      checkBox.Checked = true;
                  }
                  break;
            }
       }
   }
 }

Step 4: Save the document to file in XML or Microsoft Word format.

[C#]
//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Fill FormField

Full Source Code for Fill FormField:

[C#]
namespace FillFormField
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //open form
            Document document = new Document(@"..\..\..\..\..\..\Data\UserForm.doc");

            //load data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\User.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");

                //fill data
                foreach (FormField field in document.Sections[0].Body.FormFields)
                {
                    String path = String.Format("{0}/text()", field.Name);
                    XPathNavigator propertyNode = user.SelectSingleNode(path);
                    if (propertyNode != null)
                    {
                        switch (field.Type)
                        {
                            case FieldType.FieldFormTextInput:
                                field.Text = propertyNode.Value;
                                break;

                            case FieldType.FieldFormDropDown:
                                DropDownFormField combox = field as DropDownFormField;
                                for(int i = 0; i < combox.DropDownItems.Count; i++)
                                {
                                    if (combox.DropDownItems[i].Text == propertyNode.Value)
                                    {
                                        combox.DropDownSelectedIndex = i;
                                        break;
                                    }
                                    if (field.Name == "country" && combox.DropDownItems[i].Text == "Others")
                                    {
                                        combox.DropDownSelectedIndex = i;
                                    }
                                }
                                break;

                            case FieldType.FieldFormCheckBox:
                                if (Convert.ToBoolean(propertyNode.Value))
                                {
                                    CheckBoxFormField checkBox = field as CheckBoxFormField;
                                    checkBox.Checked = true;
                                }
                                break;
                        }
                    }
                }
            }

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
Friday, 06 December 2013 02:29

Create Form Fields in Word Document in C#

MS Word document form field is often used to display, catch and edit data. We can create a form in Microsoft Office Word with a template and adding content controls, including text boxes, date pickers, and drop-down lists. Without installing Microsoft Office, developers can use Spire.Doc to add fields and create form in word document in C#.

Here comes to the details of how developers create FormField by using Spire.Doc:

  • Download Spire.Doc for .NET (or Spire.Office for .NET) and install it on your system.
  • Add Spire.Doc.dll as reference in the downloaded Bin folder through the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Step 1: Create a word document.

//Create a word document
Document document = new Document();

Step 2: Add new section to document, and we will give details about Form section. There are three mainly fields in the form: text, dropdown list and check box.

//Add new section to document
Section section = document.AddSection();

//Add Form to section
private void AddForm(Section section)

//add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

//add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

//add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);

Step 3: Save the document to file in Microsoft word format.

//Save doc file
document.SaveToFile("Sample.doc",FileFormat.Doc);

Effective Screenshot:

Create FormField

Full Source Code for Create FormField:

namespace CreateFormField
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Document document = new Document();
            Section section = document.AddSection();

            //page setup
            SetPage(section);

            //insert header and footer.
            InsertHeaderAndFooter(section);

            //add title
            AddTitle(section);

            //add form
            AddForm(section);

            //protect document, only form fields could be edited.
            document.Protect(ProtectionType.AllowOnlyFormFields, "e-iceblue");

            //Save doc file.
            document.SaveToFile("Sample.doc",FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");

        }

        private void SetPage(Section section)
        {
            //the unit of all measures below is point, 1point = 0.3528 mm
            section.PageSetup.PageSize = PageSize.A4;
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 89.85f;
            section.PageSetup.Margins.Right = 89.85f;
        }

        private void InsertHeaderAndFooter(Section section)
        {
            //insert picture and text to header
            Paragraph headerParagraph = section.HeadersFooters.Header.AddParagraph();
            DocPicture headerPicture
                = headerParagraph.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\Data\Header.png"));

            //header text
            TextRange text = headerParagraph.AppendText("Demo of Spire.Doc");
            text.CharacterFormat.FontName = "Arial";
            text.CharacterFormat.FontSize = 10;
            text.CharacterFormat.Italic = true;
            headerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;

            //border
            headerParagraph.Format.Borders.Bottom.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            headerParagraph.Format.Borders.Bottom.Space = 0.05F;

            //header picture layout - text wrapping
            headerPicture.TextWrappingStyle = TextWrappingStyle.Behind;

            //header picture layout - position
            headerPicture.HorizontalOrigin = HorizontalOrigin.Page;
            headerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left;
            headerPicture.VerticalOrigin = VerticalOrigin.Page;
            headerPicture.VerticalAlignment = ShapeVerticalAlignment.Top;

            //insert picture to footer
            Paragraph footerParagraph = section.HeadersFooters.Footer.AddParagraph();
            DocPicture footerPicture
                = footerParagraph.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\Data\Footer.png"));

            //footer picture layout
            footerPicture.TextWrappingStyle = TextWrappingStyle.Behind;
            footerPicture.HorizontalOrigin = HorizontalOrigin.Page;
            footerPicture.HorizontalAlignment = ShapeHorizontalAlignment.Left;
            footerPicture.VerticalOrigin = VerticalOrigin.Page;
            footerPicture.VerticalAlignment = ShapeVerticalAlignment.Bottom;

            //insert page number
            footerParagraph.AppendField("page number", FieldType.FieldPage);
            footerParagraph.AppendText(" of ");
            footerParagraph.AppendField("number of pages", FieldType.FieldNumPages);
            footerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;

            //border
            footerParagraph.Format.Borders.Top.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            footerParagraph.Format.Borders.Top.Space = 0.05F;
        }

        private void AddTitle(Section section)
        {
            Paragraph title = section.AddParagraph();
            TextRange titleText = title.AppendText("Create Your Account");
            titleText.CharacterFormat.FontSize = 18;
            titleText.CharacterFormat.FontName = "Arial";
            titleText.CharacterFormat.TextColor = Color.FromArgb(0x00, 0x71, 0xb6);
            title.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Center;
            title.Format.AfterSpacing = 8;
        }

        private void AddForm(Section section)
        {
            ParagraphStyle descriptionStyle = new ParagraphStyle(section.Document);
            descriptionStyle.Name = "description";
            descriptionStyle.CharacterFormat.FontSize = 12;
            descriptionStyle.CharacterFormat.FontName = "Arial";
            descriptionStyle.CharacterFormat.TextColor = Color.FromArgb(0x00, 0x45, 0x8e);
            section.Document.Styles.Add(descriptionStyle);

            Paragraph p1 = section.AddParagraph();
            String text1
                = "So that we can verify your identity and find your information, "
                + "please provide us with the following information. "
                + "This information will be used to create your online account. "
                + "Your information is not public, shared in anyway, or displayed on this site";
            p1.AppendText(text1);
            p1.ApplyStyle(descriptionStyle.Name);

            Paragraph p2 = section.AddParagraph();
            String text2
                = "You must provide a real email address to which we will send your password.";
            p2.AppendText(text2);
            p2.ApplyStyle(descriptionStyle.Name);
            p2.Format.AfterSpacing = 8;

            //field group label style
            ParagraphStyle formFieldGroupLabelStyle = new ParagraphStyle(section.Document);
            formFieldGroupLabelStyle.Name = "formFieldGroupLabel";
            formFieldGroupLabelStyle.ApplyBaseStyle("description");
            formFieldGroupLabelStyle.CharacterFormat.Bold = true;
            formFieldGroupLabelStyle.CharacterFormat.TextColor = Color.White;
            section.Document.Styles.Add(formFieldGroupLabelStyle);

            //field label style
            ParagraphStyle formFieldLabelStyle = new ParagraphStyle(section.Document);
            formFieldLabelStyle.Name = "formFieldLabel";
            formFieldLabelStyle.ApplyBaseStyle("description");
            formFieldLabelStyle.ParagraphFormat.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;
            section.Document.Styles.Add(formFieldLabelStyle);

            //add table
            Table table = section.AddTable();

            //2 columns of per row
            table.DefaultColumnsNumber = 2;

            //default height of row is 20point
            table.DefaultRowHeight = 20;

            //load form config data
            using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\Form.xml"))
            {
                XPathDocument xpathDoc = new XPathDocument(stream);
                XPathNodeIterator sectionNodes = xpathDoc.CreateNavigator().Select("/form/section");
                foreach (XPathNavigator node in sectionNodes)
                {
                    //create a row for field group label, does not copy format
                    TableRow row = table.AddRow(false);
                    row.Cells[0].CellFormat.BackColor = Color.FromArgb(0x00, 0x71, 0xb6);
                    row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                    //label of field group
                    Paragraph cellParagraph = row.Cells[0].AddParagraph();
                    cellParagraph.AppendText(node.GetAttribute("name", ""));
                    cellParagraph.ApplyStyle(formFieldGroupLabelStyle.Name);

                    XPathNodeIterator fieldNodes = node.Select("field");
                    foreach (XPathNavigator fieldNode in fieldNodes)
                    {
                        //create a row for field, does not copy format
                        TableRow fieldRow = table.AddRow(false);

                        //field label
                        fieldRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        Paragraph labelParagraph = fieldRow.Cells[0].AddParagraph();
                        labelParagraph.AppendText(fieldNode.GetAttribute("label", ""));
                        labelParagraph.ApplyStyle(formFieldLabelStyle.Name);

                        fieldRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        Paragraph fieldParagraph = fieldRow.Cells[1].AddParagraph();
                        String fieldId = fieldNode.GetAttribute("id", "");
                        switch (fieldNode.GetAttribute("type", ""))
                        {
                            case "text":
                                //add text input field
                                TextFormField field
                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;

                                //set default text
                                field.DefaultText = "";
                                field.Text = "";
                                break;

                            case "list":
                                //add dropdown field
                                DropDownFormField list
                                    = fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;

                                //add items into dropdown.
                                XPathNodeIterator itemNodes = fieldNode.Select("item");
                                foreach (XPathNavigator itemNode in itemNodes)
                                {
                                    list.DropDownItems.Add(itemNode.SelectSingleNode("text()").Value);
                                }
                                break;

                            case "checkbox":
                                //add checkbox field
                                fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);
                                break;
                        }
                    }

                    //merge field group row. 2 columns to 1 column
                    table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1);
                }
            }
        }

        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

    }
}
Thursday, 05 December 2013 08:10

How to Unmerge Excel Cells in C#

Unmerging and merging Excel cells are indispensable for handling Excel worksheet. This article aims at introducing the solution to unmerge Excel cells in c# through several lines of code. We need an Excel .NET component called Spire.XLS to help us complete the process.

First we need to complete the preparatory work before unmerge Excel cells in C#:

  • 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.

Here comes to the explanation of the code:

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

Workbook book = new Workbook();

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

book.LoadFromFile(@"..\..\abc.xlsx");

Step 3: Get the first worksheet.

Worksheet sheet = book.Worksheets[0];

Step 4: Unmerge the cells.

sheet.Range["A2"].UnMerge();

Step5: Save as the generated file.

book.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);

Here is the whole code:

static void Main(string[] args)
        {
            Workbook book = new Workbook();
            book.LoadFromFile(@"..\..\abc.xlsx");
            Worksheet sheet = book.Worksheets[0];
            sheet.Range["A2"].UnMerge();
            book.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);
        }

Please preview the original effect screenshot:

unmerge_the_cell_01

And the generated effect screenshot:

unmerge_the_cell_02

Like word, data stored in Excel has format. Sometimes, we need to change the format of the data. Spire.XLS, an easy but powerful Excel .NET component can meet your need both in data dealing and format settings.

In this article, we will introduce you how to alternate row colors with conditional formatting.

Step 1: Select the range that you want to format

CellRange dataRange = sheet.AllocatedRange;

Step 2: Set conditional formation

Call the method AddCondition to add a new conditional formatting instance format1.

  • FirstFormula : It determines which cells to format.
  • FormatType : Set conditional formatting type
  • BackColor : Set as LightSeaGreen.
  • format1 sets the backcolor of the even rows as LightSeaGreen.
ConditionalFormatWrapper format1 = dataRange.ConditionalFormats.AddCondition();
format1.FirstFormula = "=MOD(ROW(),2)=0";
format1.FormatType = ConditionalFormatType.Formula;
format1.BackColor = Color.LightSeaGreen;

format2 sets the backcolor of the odd rows as Yellow.

Full code:

static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            CellRange dataRange = sheet.AllocatedRange;

            ConditionalFormatWrapper format1 = dataRange.ConditionalFormats.AddCondition();
            format1.FirstFormula = "=MOD(ROW(),2)=0";
            format1.FormatType = ConditionalFormatType.Formula;
            format1.BackColor = Color.LightSeaGreen;

            ConditionalFormatWrapper format2 = dataRange.ConditionalFormats.AddCondition();
            format2.FirstFormula = "=MOD(ROW(),2)=1";
            format2.FormatType = ConditionalFormatType.Formula;
            format2.BackColor = Color.Yellow;

            workbook.SaveToFile("result.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("result.xlsx");

        }

Screenshot:

How to Alternate Row Colors in Excel with Conditional Formatting

Thursday, 28 November 2013 08:37

How to Set Excel Print Options in C#

Excel print options (also called as sheet options) allow users to control how worksheet pages are printed, such as set print paper size, print area, print titles, page order and so on. This article mainly discusses how developers set print options in C# by using Spire.XLS.

Here comes to the details of how developers configure print options in C#:

  • Download Spire.XLS for .NET (or Spire.Office for .NET) and install it on your system.
  • Add Spire.XLS.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.XLS\Bin\NET4.0\ Spire.XLS.dll".
  • You can use the class PageSetup to set the print options.

Set print paper size:

By default, the paper size is A4; you can set the PaperSize property of the worksheet to set the print paper size you desired.

//set print paper size as A3
sheet.PageSetup.PaperSize = PaperSizeType.PaperA3;

Set Print Area:

By default, the print area means all areas of the worksheet that contain data. You can set the PrintArea property of the worksheet to set the print area you want.

//set print area from cell "B2" to cell "F8"
sheet.PageSetup.PrintArea = "B2:F8";

Set Print Titles:

Spire.XLS allows you to designate row and column headers to repeat on all pages of a printed worksheet. To do so, use the PageSetup class' PrintTitleColumns and PrintTitleRows properties.

//Set column numbers A & B as title columns
sheet.PageSetup.PrintTitleColumns = "$A:$B";

//Set row numbers 1 & 2 as title rows
sheet.PageSetup.PrintTitleRows = "$1:$2";

Set Page Order:

The PageSetup class provides the Order property that is used to order multiple pages of your worksheet to be printed. There are two possibilities to order the pages as follows:

//set page order from down then over
sheet.PageSetup.Order = OrderType.DownThenOver;

//set page order from over then down
sheet.PageSetup.Order = OrderType.OverThenDown;

Below picture shows the Microsoft Excel's page print options:

Spire.xls for printing PageSetup

Friday, 22 November 2013 08:01

Merge PDF Files with New Method in C#

Using Spire.PDF, you can split or merge PDF files easily and conveniently.In this article, we will introduce you a new method to merge PDF files.

[C#]
public static PdfDocumentBase MergeFiles(string[] InputFiles)

Paremeters:

  • Inputfiles, an array stores the names of files to merge.
  • Return value, a PdfDocumentBase object containing merged documents.

The new method is easier and more practical than the old ones. And it can merge many files without considering the structure of the files.

Bellowing is complete code:

[C#]
String[] files = new String[] { "Sample1.pdf", "Sample2.pdf", "Sample3.pdf" };          
string outputFile = "result.pdf";
PdfDocumentBase doc = PdfDocument.MergeFiles(files);
doc.Save(outputFile, FileFormat.PDF);
[VB.NET]
Dim files As String() = New String() {"Sample1.pdf", "Sample2.pdf", "Sample3.pdf"}
Dim outputFile As String = "result.pdf"
Dim doc As PdfDocumentBase = PdfDocument.MergeFiles(files)
doc.Save(outputFile, FileFormat.PDF)

PS: To use PdfDocument.MergeFiles you will need to add reference System.Web.dll to your project. Otherwise, you will get an error.

Effect Screenshots:

merge_pdf_files

result_pdf

Thursday, 21 November 2013 09:10

How to Convert Excel to Text in C#, VB.NET

This article aims at introducing an easy solution to convert Excel (xls/xlsx) to Text in C# and VB.NET by a powerful and independent Excel .NET component, called Spire.Xls. Meanwhile, this Excel API supports for converting Excel (xls/xlsx) to PDF, HTML, Image, CSV, XML, etc, without Microsoft Excel installed on the machine. Download it from here to have a try.

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

Workbook workbook = new Workbook();

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

workbook.LoadFromFile(@"..\ExceltoTxt.xls");

Step 3: Get the first worksheet of the Worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 4: Save the document object to a Txt file.

sheet.SaveToFile("ExceltoTxt.txt", " ", Encoding.UTF8);

Effect Screenshot:

Excel_to_Txt

Excel_to_Txt

Sample code:

[C#]
using Spire.Xls;
namespace Excel_to_Txt
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"..\ExceltoTxt.xls");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.SaveToFile("ExceltoTxt.txt", " ", Encoding.UTF8);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace Excel_to_Txt
       Friend Class Program
              Shared Sub Main(ByVal args() As String)
                     Dim workbook As New Workbook()
                     workbook.LoadFromFile("..\ExceltoTxt.xls ")
                     Dim sheet As Worksheet = workbook.Worksheets(0)
                     sheet.SaveToFile("ExceltoTxt.txt", " ", Encoding.UTF8)
              End Sub
       End Class
End Namespace
Page 3 of 22