Friday, May 16, 2014

Create PDF file from scratch using Spire.PDF


Previewscreenshot of the result PDF file.



Here is the code to create the above PDF file. Just use the API and test the following code, PDF file will be successfully created. And I hope this article can do you some help.
//create a pdf document.
PdfDocument doc = newPdfDocument();

// create one page
PdfPageBase page = doc.Pages.Add();
floatpageWidth = page.Canvas.ClientSize.Width;
float y = 0;

//page header
PdfPen pen1 = newPdfPen(Color.LightGray, 1f);
PdfBrush brush1 = newPdfSolidBrush(Color.LightGray);
PdfTrueTypeFont font1 = newPdfTrueTypeFont(newFont("Arial", 8f, FontStyle.Italic));
PdfStringFormat format1 = newPdfStringFormat(PdfTextAlignment.Right);
String text = "Demo of Barcode";
page.Canvas.DrawString(text, font1, brush1, pageWidth, y, format1);
SizeF size = font1.MeasureString(text, format1);
y = y + size.Height + 1;
page.Canvas.DrawLine(pen1, 0, y, pageWidth, y);

//title
y = y + 5;
PdfBrush brush2 = newPdfSolidBrush(Color.Black);
PdfTrueTypeFont font2 = newPdfTrueTypeFont(newFont("Arial", 16f, FontStyle.Bold));
PdfStringFormat format2 = newPdfStringFormat(PdfTextAlignment.Center);
format2.CharacterSpacing = 1f;
text = "Summary of Science";
page.Canvas.DrawString(text, font2, brush2, pageWidth / 2, y, format2);
size = font2.MeasureString(text, format2);
y = y + size.Height + 6;

//add barcode
PdfCode128BBarcode barcode = newPdfCode128BBarcode("Hello 00-123");
barcode.BarHeight = 20;
barcode.BarcodeToTextGapHeight = 1f;
barcode.TextDisplayLocation = TextLocation.Bottom;
barcode.TextColor = Color.Blue;
barcode.Draw(page, newPointF(0, y));
y = y + 30;

//add picture
PdfImage image = PdfImage.FromFile("Science.png");
page.Canvas.DrawImage(image, newPointF(pageWidth - image.PhysicalDimension.Width, y));
floatimageLeftSpace = pageWidth - image.PhysicalDimension.Width - 2;
floatimageBottom = image.PhysicalDimension.Height + y;

//add text content
PdfStringFormat format4 = newPdfStringFormat();
text = System.IO.File.ReadAllText("ScienceText.txt");
PdfTrueTypeFont font5 = newPdfTrueTypeFont(newFont("Arial", 10f));
format4.LineSpacing = font5.Size * 1.5f;
PdfStringLayoutertextLayouter = newPdfStringLayouter();
floatimageLeftBlockHeight = imageBottom - y;
PdfStringLayoutResult result
    = textLayouter.Layout(text, font5, format4, newSizeF(imageLeftSpace, imageLeftBlockHeight));
if (result.ActualSize.Height<imageBottom - y)
{
imageLeftBlockHeight = imageLeftBlockHeight + result.LineHeight;
result = textLayouter.Layout(text, font5, format4, newSizeF(imageLeftSpace, imageLeftBlockHeight));
}
foreach (LineInfo line inresult.Lines)
{
page.Canvas.DrawString(line.Text, font5, brush2, 0, y, format4);
    y = y + result.LineHeight;
}
PdfTextWidgettextWidget = newPdfTextWidget(result.Remainder, font5, brush2);
PdfTextLayouttextLayout = newPdfTextLayout();
textLayout.Break = PdfLayoutBreakType.FitPage;
textLayout.Layout = PdfLayoutType.Paginate;
RectangleF bounds = newRectangleF(newPointF(0, y), page.Canvas.ClientSize);
textWidget.StringFormat = format4;
textWidget.Draw(page, bounds, textLayout);

//save pdf file.
doc.SaveToFile("result.pdf");
doc.Close();

//view the result file
System.Diagnostics.Process.Start("result.pdf");

Tuesday, May 6, 2014

How to Convert Word to PDF for Free in C#

This is an all-in-one solution to convert Word to PDF. Within this solution, you can either create a word from scratch or load a word template from folder, and then edit the document as you like; finally you can effortlessly convert word to PDF in C#, VB.NET. The conversion can be doc or docxto PDF.
Free Spire.Doc for .NET is a Community Edition of the Spire.Doc for .NET. It is a free.NET word library which enables users to directly manage word editing without Microsoft Word being installed, after the editing, you can convert the document to PDF in 2 steps.

Below is an effective screenshot of the document which will be converted to PDF. At the end of this post, you can find the target PDFdocument.
Now download the free version of Spire.Doc for .NET and convert word to PDF for personal use or evaluation. The whole process of converting word to PDF in C#, VB.NET can be described as 2 simple steps.
1. Declare a document and load document which you prepare by using ocument.LoadFromFile() method. The parameter passed to this method is file name string.
2. Save Word document as PDF by using document.SaveToFile() method. Parameters passed to this method is file name string and file format. The file format must be PDF.
[C#]
using System;
using Spire.Doc;
usingSpire.Doc.Documents;
namespaceDoctoPDF

{
classProgram
    {
staticvoid Main(string[] args)
{

Documentdocument = newDocument();
document.LoadFromFile("Word.doc"); 

//Convert Word to PDF 
document.SaveToFile("toPDF.PDF", FileFormat.PDF);

//Launch Document 
System.Diagnostics.Process.Start("toPDF.PDF"); 
        }
    }
}
[VB]
mports System

Imports Spire.Doc 

ImportsSpire.Doc.Documents

NamespaceDoctoPDF
FriendClasstoPDF
SharedSubMain(ByValargs() AsString)

'Load Document 
Dim document AsNewDocument()
document.LoadFromFile("E:\work\documents\TestSample.docx")

'Convert Word to PDF 
document.SaveToFile("toPDF.PDF", FileFormat.PDF)

'Launch Document 

System.Diagnostics.Process.Start("toPDF.PDF")

EndSub

EndClass

EndNamespace
After running the demo, you may find a PDF document launched on your computer:


C# word operate conclusion Spire.doc

For the recent project requirements, we need to do some processing on the word document. We did a lot of search online, and found that most of them are incomplete and repeated. Few of complete guides for word component are not free. Finally I am lucky to find a free C# word library to meet all my requirements. In order to prepare others to use it later, I make a conclusion as below. Wish it helps.

How to get it?
This free word component is listed on the Codeplex, you can get the msi file directly from there. It also offers some source code.

Operate word document conclusion.

1.       Open an existing word document. This is the basic and must step to process the word document. And it offers 3 different ways.
Solution1: Initialize a new instance of Document class from the specified existing document.
Document document = new Document(@"..\..\Sample.docx");

Solution2: Load a word document from the file.
Document document = new Document();
document.LoadFromFile(@"..\..\Sample.docx");
       
Solution3: Load word document from Stream
Stream stream = File.OpenRead(@"..\..\Sample.docx");
Document document = new Document(stream);

2. How to create Table:
Document document = new Document();
Section section = document.AddSection();

Table table = section.AddTable(true);
table.ResetCells(2, 3);

TableRow row = table.Rows[0];
row.IsHeader = true;

Paragraph para = row.Cells[0].AddParagraph();
TextRange TR = para.AppendText("Item");

para = row.Cells[1].AddParagraph();
TR = para.AppendText("Description");

para = row.Cells[2].AddParagraph();
TR = para.AppendText("Qty");

document.SaveToFile("WordTable.docx");

System.Diagnostics.Process.Start("WordTable.docx");








We can also set the rows and cells board and height.

3. How to insert hyperlinks. You can insert two types of hyperlinks, Email link and webmail link.
Document document = new Document();
Section section = document.AddSection();

//Insert URL hyperlink
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home page");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);

//Insert email address hyperlink
paragraph = section.AddParagraph();
paragraph.AppendText("Contact US");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "support@e-iceblue.com", HyperlinkType.EMailLink);

document.SaveToFile("Hyperlink.docx");
System.Diagnostics.Process.Start("Hyperlink.docx");

4. How to add comments.

Document document = new Document();
Section section = document.AddSection();

Paragraph paragraph = section.AddParagraph();
paragraph.AppendText("Home Page of ");
TextRange textRange = paragraph.AppendText("e-iceblue");

Comment comment1 = paragraph.AppendComment("www.e-iceblue.com");
comment1.AddItem(textRange);
comment1.Format.Author = "Harry Hu";
comment1.Format.Initial = "HH";

document.SaveToFile("Comment.docx");
System.Diagnostics.Process.Start("Comment.docx");



5. How to add bookmarks:

Document document = new Document();
Section section = document.AddSection();

Paragraph paragraph = section.AddParagraph();

paragraph.AppendBookmarkStart("SimpleBookMark");
paragraph.AppendText("This is a simple book mark.");
paragraph.AppendBookmarkEnd("SimpleBookMark");

document.SaveToFile("Bookmark.docx");
System.Diagnostics.Process.Start("Bookmark.docx");

6. MailMerge

Document document = new Document();
document.LoadFromFile("Fax.doc");

string[] filedNames = new string[] { "Contact Name", "Fax", "Date" };

string[] filedValues = new string[] { "John Smith", "+1 (69) 123456", System.DateTime.Now.Date.ToString() };

document.MailMerge.Execute(filedNames, filedValues);

document.SaveToFile("MailMerge.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("MailMerge.doc");

7. FormField. This part contains create and fill formfield.
Create FormField:
//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);


Fill FormField:
//Fill data from XML file
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;
            }
       }
   }
 }

8. Merge word document.
//Load two documents
//Load Document1 and Document2
Document DocOne = new Document();
DocOne.LoadFromFile(@"E:\Work\Document\welcome.docx", FileFormat.Docx);
Document DocTwo = new Document();
DocTwo.LoadFromFile(@"E:\Work\Document\New Zealand.docx", FileFormat.Docx);

//Merge
foreach (Section sec in DocTwo.Sections)
{
 DocOne.Sections.Add(sec.Clone());
}
//Save and Launch
DocOne.SaveToFile("Merge.docx", FileFormat.Docx);

9. Protect document. You can set password or add watermarks to the word document to protect the document. Both text and image watermarks supported.

//Protect with password
document.Encrypt("eiceblue");

//Add Text watermark:
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = "Microsoft";
txtWatermark.FontSize = 90;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;

//Add Image watermark:
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile(@"..\imagess.jpeg");
picture.Scaling = 250;
document.Watermark = picture;

10. Conversion function is the most popular requirements for processing word documents. With the help of free Spire.Doc for .net, conversion becomes very simple and easy. Only three same lines code is involved and you can convert word document to often used formats, such as PDF, HTML and Image.

Convert word document to PDF

document.SaveToFile("Target PDF.PDF", FileFormat.PDF);

Convert word document to Image

Image image = document.SaveToImages(0, ImageType.Bitmap);
image.Save("Sample.tiff", ImageFormat.Tiff);

Convert word document to HTML:

document.SaveToFile("Target HTML.html", FileFormat.Html);
WordDocViewer(""Target HTML.html");

Conclusion: This is a powerful and free C# word component without Word automation and any other third party add-ins.