Insert Image and Formatted Text in Excel Header or Footer in C#

Excel header or footer, which presents information like page numbers, the creation date, the logo of your company, and even customized text, can be of use in printed worksheets. In this article, you’ll learn how to insert images and formatted text in Excel header or footer in C#.

This solution relies on Spire.XLS, an Excel processing library, which provides a PageSetup class to deal with all page setup settings. Specifically, it contains LeftHeader, CenterHeader, LeftHeaderImage, OddHeaderStringand similar properties that represent header/footer text, image, odd header/footer and even header/footer in Excel. Besides, this component provides some special script commands, which are used to get the dynamic value like page number or format the header or footer text.

Script D
&P The current page number
&N The total number of pages
&D The current data
&T The current time
&G A picture
&A The worksheet name
&F The file name
&B Make text bold
&I Italicize text
&U Underline text
&”font name” Represents a font name, for example, &”Aril”
&font size Represents font size, for example, &12
&K Represents font color, for example, &KFF0000

Insert Image to Header

  //create a word document
Workbook wb = new Workbook();

//get the first worksheet
Worksheet sheet = wb.Worksheets[0];

//load a pic to Image object
Image image = Image.FromFile("company-logo.jpg");

//scale the image
Bitmap bitmap = new Bitmap(image, new Size(image.Width / 4, image.Height / 4));

//insert image to left header
sheet.PageSetup.LeftHeaderImage = bitmap;
sheet.PageSetup.LeftHeader = "&G";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);

2017-06-26_152908

Insert Formatted Text to Footer

 //create an object of Workbook class   
Workbook wb = new Workbook();

//get the first sheet  
Worksheet sheet = wb.Worksheets[0];

//format a string with script commands and assign it to CenterFooter   
sheet.PageSetup.CenterFooter = "&\"Arial\"&B&12&KFF0000Copyright © 2017 JMD. All Rights Reserved.";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);

2017-06-26_153656

Convert PPT/PPTX to PNG in C#

It is not uncommon that we may need to convert a PowerPoint file to images or a PDF file in our work. In my previous post, I have introduced how to export PPT/PPTX files as PDFs. This article will introduce how we can convert a PPT/PPTX file into PNGs by using Spire.Presentation in C#.

Here come the code snippets:


using Spire.Presentation;
using System.Drawing;

namespace Conversion
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of Presentation class
            Presentation presentation = new Presentation();

            //Load a PowerPoint document
            presentation.LoadFromFile("Template.pptx");

            //Traverse each slide in PowerPoint and save as png image
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                Image image = presentation.Slides[i].SaveAsImage();
                String fileName = String.Format("Result-{0}.png", i);
                image.Save(fileName);
            }
        }
    }
}

Output

2017-05-08_152546

Convert HTML String to PDF using Free API in C#

Converting from HTML to PDF is not an easy task. There are some tools that can do this, but most of them costs thousands of dollars. This article provides a free solution with only few lines of C# code, using free Spire.PDF.

Free Spire.PDF is a community edition of the fully featured Spire.PDF for .NET. It allows you to create PDF documents directly from HTML pages in your ASP.NET and MVC Websites, Desktop Applications and Services.

You can use the free library in .NET 4.0 and later applications, in C# and VB.NET languages, on 32-bit and 64-bit Windows machines.

2017-02-07_144504

Using the code

PdfDocument pdf = new PdfDocument();
PdfPageSettings setting = new PdfPageSettings();
setting.Size = PdfPageSize.A4;

PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
htmlLayoutFormat.IsWaiting = false;                    
string htmlCode = File.ReadAllText("HTML example.html");
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

pdf.SaveToFile("Html2Pdf.pdf");

Output

2017-02-07_144945

How to Print PDF to XPS in C#/VB.NET

Windows 7 comes with a Microsoft XPS Document Writer (MXDW) printer which can be used to print any document to an XPS file. It is also included in later releases, such as Windows 10. This article will introduce how to programmatically connect MXDW and print a PDF file into a XPS file.

To use following code snippets to print PDF file, you need to install Spire.PDF via NuGet and add the dll files into .NET assemblies.

Code Snippets

using Spire.Pdf;
namespace PrintPdfToXps
{
    class Program
    {
        static void Main(string[] args)
        {
            //load a Pdf document
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"example.pdf");

            //specify printer 
            doc.PrintDocument.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
            //print Pdf to a file instead a port
            doc.PrintDocument.PrinterSettings.PrintToFile = true;
            doc.PrintDocument.PrinterSettings.PrintFileName = "PrintToXps.xps";

            //start printing process
            doc.PrintDocument.Print();
        }
    }
}

Split Word Documents by Page Breaks or Section Breaks in C#

Page breaks and section breaks are two useful features for controlling page layout in MS Word and other desktop publishing programs. Page breaks are used to end a page without filling it with text. Section breaks are used to allow formatting changes (i.e., different margins, page number styles, etc.) in the same document.

Sometimes, we may want to pull the different parts that are separated by page breaks or section breaks out of the whole document storing as several individual files. This article provides two brilliant solutions in C# to split a Word document by page breaks and section breaks.

Split by Page Breaks

using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Split_Word_Document_by_Page_Break
{
    class Program
    {
        static void Main(string[] args)
        {
            Document original = new Document();
            original.LoadFromFile("New Zealand.docx");
            Document newWord = new Document();
            Section section = newWord.AddSection();

            int index = 0;
            foreach (Section sec in original.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph para = obj as Paragraph;
                        section.Body.ChildObjects.Add(para.Clone());

                        foreach (DocumentObject parobj in para.ChildObjects)
                        {
                            if (parobj is Break && (parobj as Break).BreakType == BreakType.PageBreak)
                            {
                                int i = para.ChildObjects.IndexOf(parobj);
                                section.Body.LastParagraph.ChildObjects.RemoveAt(i);
                                newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
                                index++;

                                newWord = new Document();
                                section = newWord.AddSection();
                                section.Body.ChildObjects.Add(para.Clone());
                                if (section.Paragraphs[0].ChildObjects.Count == 0)
                                {
                                    section.Body.ChildObjects.RemoveAt(0);
                                }
                                else
                                {
                                    while (i >= 0)
                                    {
                                        section.Paragraphs[0].ChildObjects.RemoveAt(i);
                                        i--;
                                    }
                                }
                            }
                        }
                    }
                    if (obj is Table)
                    {
                        section.Body.ChildObjects.Add(obj.Clone());
                    }
                }
            }
            newWord.SaveToFile(String.Format("result/out-{0}.docx", index), FileFormat.Docx);
        }
    }
}

Split by Section Breaks

using System;
using Spire.Doc;

namespace Split_Word_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Test.doc");
            Document newWord;
            for (int i = 0; i < document.Sections.Count; i++)
            {
                newWord = new Document();
                newWord.Sections.Add(document.Sections[i].Clone());
                newWord.SaveToFile(String.Format(@"test\out_{0}.docx", i));
            }
        }
    }
}

Note: These solutions are relied on free .NET Word Component, you can download it from here and reference the DLL file to your own project.