Convert Word Document to PDF in ASP.Net MVC

Last Reply 7 months ago By dharmendr

Posted 7 months ago

How i can convert doc file into pdf in asp.net mvc.

You are viewing reply posted by: dharmendr 7 months ago.
Posted 7 months ago Modified on 7 months ago

Hi khushboo,

Check this example. Now please take its reference and correct your code.

For this example i have used Microsoft.Office.Interop library. You need to add the Microsoft.Office.Interop library reference in your projet.

Namespaces

using Word = Microsoft.Office.Interop.Word;

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public FileResult Convert(HttpPostedFileBase postedFile)
    {
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(postedFile.FileName);
        string filePath = Server.MapPath("~/Files/") + Path.GetFileName(postedFile.FileName);
        postedFile.SaveAs(filePath);
        string input = filePath;
        string output = Server.MapPath("~/Files/") + fileNameWithoutExtension + ".pdf";
        ConvertWordToSpecifiedFormat(input, output, Word.WdSaveFormat.wdFormatPDF);
        return File(output, "application/pdf", fileNameWithoutExtension + ".pdf");
    }

    private static void ConvertWordToSpecifiedFormat(object input, object output, object format)
    {
        Word._Application application = new Word.Application();
        application.Visible = false;
        object missing = Missing.Value;
        object isVisible = true;
        object readOnly = false;
        Word._Document document = application.Documents.Open(ref input, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);

        document.Activate();
        document.SaveAs(ref output, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        application.Quit(ref missing, ref missing, ref missing);
    }
}

View

<div>
    <%using (Html.BeginForm("Convert", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
    <input type="file" name="postedFile" /><br /><br />
    <input type="submit" value="Convert Word To PDF" />
    <% } %>
</div>

Screenshots

The Word File

The converted PDF