Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to Replace the word document Text and Save as PDF in Memory stream and Open from Memory Stream.
Posted

 
Share this answer
 
C#
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);
            }
        }


Regard
Sham
 
Share this answer
 
v2
Comments
Robymon 20-Aug-12 4:09am    
what is the Target, Can i put like this,
object Target = System.Web.HttpContext.Current.Server.MapPath("~/Project/Temp.PDF");
Shambhoo kumar 20-Aug-12 4:13am    
Yes...
XML
Explanation:

  Here i used Microsoft.Office.Interop.word dll. This one in-built dll while installing Visual studio 2008 & above.



  Also How to convert aspx to word and word to PDF.

  And also after converted our pdf document to send e-mail with pdf attachment through GMAIL.

For converting to PDF & Send Mail u must follow the steps:

 This is the 2007 Microsoft Office Add-in: Microsoft Save as PDF.

we should download this add-in and install to our machine.

It's must for Installed on where pdf coding is running.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=9943

And also

do in Page Directive that  EnableEventValidation="false"  It's must. because here i used RendorControl. It throws error. after that declaration of this that error won't come again.

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PDF._Default" EnableEventValidation="false" %>

Step 1:

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PDF._Default" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="0" cellpadding="0" cellspacing="0" width="1258px" align="center">
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="btn_PDF" runat="server" Text="PDF" OnClick="btn_PDF_Click" />
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td align="center">
<asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="False"
ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country Code">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Ccode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State Code">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("SCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City Code">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("CyCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td align="center">
<asp:Image ID="Img1" runat="server" ImageUrl="../Images/Koala.jpg" />
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td align="center">
<asp:Image ID="Img2" runat="server" ImageUrl="../Images/Tulips.jpg" />
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Step 2:

 Right click on PDF project --> Add  Reference and do instructions given by followed Images:





Step 3:

Default.aspx.cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Text;
using System.Data.SqlClient;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.Net;

namespace PDF
{
public partial class _Default : System.Web.UI.Page
{
string conStr = ConfigurationManager.ConnectionStrings["testCon"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter sqlda;
DataTable dt;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}
}

private void FillGrid()
{
using (con = new SqlConnection(conStr))
{
con.Open();
string selQry = string.Format("select top 5 ID,name,Ccode,SCode,CyCode from test_Details");
using (cmd = new SqlCommand(selQry, con))
{
sqlda = new SqlDataAdapter(cmd);
dt = new DataTable();
sqlda.Fill(dt);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}

protected void btn_PDF_Click(object sender, EventArgs e)
{
string MailId = string.Empty; //Given Mail Id by user
string EmailId = string.Empty; //Constant Mail ID
string Name = string.Empty;
string Sub_Name = string.Empty;


//Convert aspx to word
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.Page.RenderControl(htw);
string htmtags = sw.ToString();
byte[] b = new byte[htmtags.Length];
b = System.Text.Encoding.UTF8.GetBytes(htmtags);
MemoryStream ms = new MemoryStream(b, true);

string renderedPage = sw.ToString();

//End Word Convert

//Start Get Task Manager Process, if already working the WINWORD.exe process then close that process

Process[] processes = Process.GetProcessesByName("WINWORD");

foreach (Process process in processes)
{
process.Close();
process.Dispose();
}

//Defining a path with File Time


//object wordpath = HttpContext.Current.Server.MapPath(@"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".doc");
//object pdfpath = HttpContext.Current.Server.MapPath(@"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".pdf");

object wordpath = @"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".doc";
object pdfpath = @"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".pdf";


File.WriteAllText(wordpath.ToString(), renderedPage);

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();

Object oMissing = System.Reflection.Missing.Value;

wordDoc = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

word.Visible = false;
object filepath = wordpath;
Object confirmconversion = System.Reflection.Missing.Value;
Object readOnly = false;
Object oallowsubstitution = System.Reflection.Missing.Value;

wordDoc = word.Documents.Open(ref filepath, ref confirmconversion, ref readOnly, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);

word.Visible = false;

//To find out the WINWORD.exe process and set RealTime Priority to WINWORD.exe
//This is used to quick process

Process[] proces = Process.GetProcessesByName("WINWORD");

foreach (Process proc in proces)
{
proc.PriorityClass = ProcessPriorityClass.RealTime;
}

object fileFormat = WdSaveFormat.wdFormatPDF;
Object saveto = pdfpath;

//Converting Word Doc to PDF

wordDoc.SaveAs(ref saveto, ref fileFormat, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oallowsubstitution, ref oMissing,
ref oMissing);

((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);

//To terminate the alredy opend process

Process[] processe = Process.GetProcessesByName("WINWORD");

foreach (Process proce in processe)
{
proce.Close();
proce.Dispose();
}

//Start to send Mail Process [GMAIL]

MailId = "venkadeshbabu.gr@gmail.com";
Name = "VENKADESH BABU G R";
Sub_Name = "Babu";
EmailId = "veb.610@gmail.com";

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
  msg.From = new MailAddress("test@gmail.com", Name);
if (MailId.Length > 0)
{
msg.To.Add(EmailId + ',' + MailId);
}
else
{
msg.To.Add(EmailId);
}

msg.Subject = Sub_Name;

msg.Body = "Attached document";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
// smtp.Port=25; //While use in Server
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
  NetworkCredential credential = new NetworkCredential("test@gmail.com", "ur password");
smtp.Credentials = credential;
System.Net.Mail.Attachment Attachment = new System.Net.Mail.Attachment(pdfpath.ToString());
//Attachment.Name = "WebQuotes.pdf"; // set attachment name here
msg.Attachments.Add(Attachment);
smtp.Send(msg);
msg.Dispose();
File.Delete(wordpath.ToString());
File.Delete(pdfpath.ToString());
}
}
}
 
Share this answer
 
v2
Comments
CHill60 1-Mar-14 9:50am    
Reason for downvote = question is a year and a half old and already answered
Step 3:

Default.aspx.cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Text;
using System.Data.SqlClient;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.Net;

namespace PDF
{
public partial class _Default : System.Web.UI.Page
{
string conStr = ConfigurationManager.ConnectionStrings["testCon"].ConnectionString;
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter sqlda;
DataTable dt;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}
}

private void FillGrid()
{
using (con = new SqlConnection(conStr))
{
con.Open();
string selQry = string.Format("select top 5 ID,name,Ccode,SCode,CyCode from test_Details");
using (cmd = new SqlCommand(selQry, con))
{
sqlda = new SqlDataAdapter(cmd);
dt = new DataTable();
sqlda.Fill(dt);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}

protected void btn_PDF_Click(object sender, EventArgs e)
{
string MailId = string.Empty; //Given Mail Id by user
string EmailId = string.Empty; //Constant Mail ID
string Name = string.Empty;
string Sub_Name = string.Empty;


//Convert aspx to word
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.Page.RenderControl(htw);
string htmtags = sw.ToString();
byte[] b = new byte[htmtags.Length];
b = System.Text.Encoding.UTF8.GetBytes(htmtags);
MemoryStream ms = new MemoryStream(b, true);

string renderedPage = sw.ToString();

//End Word Convert

//Start Get Task Manager Process, if already working the WINWORD.exe process then close that process

Process[] processes = Process.GetProcessesByName("WINWORD");

foreach (Process process in processes)
{
process.Close();
process.Dispose();
}

//Defining a path with File Time


//object wordpath = HttpContext.Current.Server.MapPath(@"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".doc");
//object pdfpath = HttpContext.Current.Server.MapPath(@"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".pdf");

object wordpath = @"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".doc";
object pdfpath = @"C:\Users\Admin\Documents\Visual Studio 2008\Projects\PDF\PDF\DOC-PDF\Test_" + DateTime.Now.ToFileTime().ToString() + ".pdf";


File.WriteAllText(wordpath.ToString(), renderedPage);

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();

Object oMissing = System.Reflection.Missing.Value;

wordDoc = word.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

word.Visible = false;
object filepath = wordpath;
Object confirmconversion = System.Reflection.Missing.Value;
Object readOnly = false;
Object oallowsubstitution = System.Reflection.Missing.Value;

wordDoc = word.Documents.Open(ref filepath, ref confirmconversion, ref readOnly, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);

word.Visible = false;

//To find out the WINWORD.exe process and set RealTime Priority to WINWORD.exe
//This is used to quick process

Process[] proces = Process.GetProcessesByName("WINWORD");

foreach (Process proc in proces)
{
proc.PriorityClass = ProcessPriorityClass.RealTime;
}

object fileFormat = WdSaveFormat.wdFormatPDF;
Object saveto = pdfpath;

//Converting Word Doc to PDF

wordDoc.SaveAs(ref saveto, ref fileFormat, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oallowsubstitution, ref oMissing,
ref oMissing);

((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);

//To terminate the alredy opend process

Process[] processe = Process.GetProcessesByName("WINWORD");

foreach (Process proce in processe)
{
proce.Close();
proce.Dispose();
}

//Start to send Mail Process [GMAIL]

MailId = "venkadeshbabu.gr@gmail.com";
Name = "VENKADESH BABU G R";
Sub_Name = "Babu";
EmailId = "veb.610@gmail.com";

System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("test@gmail.com", Name);
if (MailId.Length > 0)
{
msg.To.Add(EmailId + ',' + MailId);
}
else
{
msg.To.Add(EmailId);
}

msg.Subject = Sub_Name;

msg.Body = "Attached document";
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
// smtp.Port=25; //While use in Server
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
NetworkCredential credential = new NetworkCredential("test@gmail.com", "ur password");
smtp.Credentials = credential;
System.Net.Mail.Attachment Attachment = new System.Net.Mail.Attachment(pdfpath.ToString());
//Attachment.Name = "WebQuotes.pdf"; // set attachment name here
msg.Attachments.Add(Attachment);
smtp.Send(msg);
msg.Dispose();
File.Delete(wordpath.ToString());
File.Delete(pdfpath.ToString());
}
}
}
 
Share this answer
 
Comments
CHill60 1-Mar-14 9:49am    
Reason for downvote = question is a year and a half old and already answered
Try iTextSharp to convert word to pdf.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900