Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp - Convert word doc/docx to pdf

I understand iTextSharp can be used for converting a document to pdf.

But first we have to create a document from scratch using iTextSharp.text.Document and then adding elements to this document.

What if I have an existing doc file, is it possible to convert this document to pdf using iTextSharp.

Also, I want to use iTextSharp or any similar tool which can perform following on a doc file:

  1. manipulation of doc/docx/text files (like replacing some placeholders with DB values) as well as
  2. converts them to .pdf

Anyone having idea about this, please share.

Thank you!

like image 613
inutan Avatar asked Oct 08 '09 10:10

inutan


2 Answers

The Aspose.Words component can do this reliably (I'm not affiliated or anything).

iTextSharp does not have the required feature set to load and process MS Word file formats.

like image 65
Lucero Avatar answered Sep 23 '22 13:09

Lucero


You can use existing method of Microsoft.Office

 private Microsoft.Office.Interop.Word.ApplicationClass MSdoc;

    //Use for the parameter whose type are not known or say Missing
    object Unknown = Type.Missing;

  private void word2PDF(object Source, object Target)
    {   //Creating the instance of Word Application
      if (MSdoc == null)MSdoc = new Microsoft.Office.Interop.Word.ApplicationClass();

        try
        {
            MSdoc.Visible = false;
            MSdoc.Documents.Open(ref Source, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown,
                 ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
             MSdoc.Application.Visible = false;
              MSdoc.WindowState =   Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateMinimize;

            object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;

            MSdoc.ActiveDocument.SaveAs(ref Target, ref format,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                    ref Unknown, ref Unknown, ref Unknown,
                   ref Unknown, ref Unknown);
          }
           catch (Exception e)
          {
            MessageBox.Show(e.Message);
           }
         finally
          {
            if (MSdoc != null)
            {
                MSdoc.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
                //WordDoc.Application.Quit(ref Unknown, ref Unknown, ref Unknown);
            }
            // for closing the application
            WordDoc.Quit(ref Unknown, ref Unknown, ref Unknown);
        }
    } 
like image 32
Shyam sundar shah Avatar answered Sep 21 '22 13:09

Shyam sundar shah