Canalblog
Editer l'article Suivre ce blog Administration + Créer mon blog
Publicité
SpireXLS
25 novembre 2011

C# - Convert Word to PDF

We can find that lots of electronic books and magazines are created with PDF and many materials shared online are PDF documents. Why people would like to use PDF? Firstly, PDF can be operated on any operation system. Secondly, PDF includes various contents, for example, special characters, image, even video. Thirdly, electronic book created by PDF can give people a feeling to read the real book. Also, readers can adjust size according to their custom. Fourthly, PDF can show formats of the original documents exactly when printing.

How to create a PDF document? We can convert from other format files. MS Word is the most frequently used format to convert to PDF because it is very powerful on text management and provides many format setting tools.

Now, I will introduce a method to convert Word to PDF with C#. This method is based on a component, Spire.Doc, which specializes in operating Word on .Net and Silverlight platform. So, before we begin with converting, we need to download and install this component on computer.

The following steps show how to convert via Spire.Doc.

  1. Add Spire.Doc DLL file as reference after creating project.
  2. Create a new blank Word document
  3. Add section and set page, including size and margin.
  4. Add paragraph with contents and set format for paragraphs.
  5. Save Word documents to PDF.

Use the code:

//Create word document

Document document = new Document();

 

Section section = document.AddSection();

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;

 

Paragraph paragraph = section.AddParagraph();

paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;

paragraph.AppendPicture(Image.FromFile("Word.png"));

 

String p1

    = "Microsoft Word is a word processor designed by Microsoft. "

    + "It was first released in 1983 under the name Multi-Tool Word for Xenix systems. "

    + "Subsequent versions were later written for several other platforms including "

    + "IBM PCs running DOS (1983), the Apple Macintosh (1984), the AT&T Unix PC (1985), "

    + "Atari ST (1986), SCO UNIX, OS/2, and Microsoft Windows (1989). ";

String p2

    = "Microsoft Office Word instead of merely Microsoft Word. "

    + "The 2010 version appears to be branded as Microsoft Word, "

    + "once again. The current versions are Microsoft Word 2010 for Windows and 2008 for Mac.";

section.AddParagraph().AppendText(p1).CharacterFormat.FontSize = 14;

section.AddParagraph().AppendText(p2).CharacterFormat.FontSize = 14;

 

//Save doc file to pdf.

document.SaveToFile("Sample.pdf", FileFormat.PDF);

Publicité
Publicité
Commentaires
SpireXLS
Publicité
Publicité