Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a dropdownlist there the user can select pdf or word extension in the dropdown, i have made it work with word interop to download , but is i possible on some way when the user select pdf, to call the word interop function, and then convert it to pdf?

here is my function for word,
C#
private void SetWordDocument()
       {


               object strFileName =
               CleanUp(LabelFirstName.Text + "_" + LabelLastName.Text + "_" + DateTime.Now.ToString("yyyy-MM-dd") + "_SWE"+
                       "." + DropDownListDownloadCv.SelectedItem.Text);

               object fs = Server.MapPath("~/Upload/") + strFileName;

               using (var db = new knowitCVdbEntities())
               {
                   var theEmpl = (from p in db.EMPLOYEES
                                  where p.username == strUserName
                                  select p).FirstOrDefault();

                   GetAlSwedishlAssigmentsDoc(theEmpl);

                   if (theEmpl != null)
                   {

                       object missing = Missing.Value;
                       object start1 = 0;

                       object oTemplate = "c:\\knowittemplate.dot";
                       var wordApp = new ApplicationClass();
                       var myDoc = wordApp.Documents.Add(ref oTemplate, ref missing, ref missing, ref missing);
                       object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
                       Range rng = myDoc.Range(ref start1, ref missing);
                       const char newLine = (char)11;
                       foreach (Field myMergeField in myDoc.Fields)
                       {

                           Range rngFieldCode = myMergeField.Code;

                           String fieldText = rngFieldCode.Text;



                           // ONLY GETTING THE MAILMERGE FIELDS

                           if (fieldText.StartsWith(" MERGEFIELD"))
                           {

                               // THE TEXT COMES IN THE FORMAT OF

                               // MERGEFIELD  MyFieldName  \\* MERGEFORMAT

                               // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

                               Int32 endMerge = fieldText.IndexOf("\\", System.StringComparison.Ordinal);

                               Int32 fieldNameLength = fieldText.Length - endMerge;

                               String fieldName = fieldText.Substring(11, endMerge - 11);

                               // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                               fieldName = fieldName.Trim();

                               // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//

                               // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

                               if (fieldName == "NAME")
                               {
                                   myMergeField.Select();
                                   wordApp.Selection.TypeText(LabelFirstName.Text + " " + LabelLastName.Text);
                               }



myDoc.SaveAs(ref fs,
                                        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, ref missing);




                           rng.InsertBefore(newLine.ToString());
                           string imageProfPic = ImageProfilePicture.ImageUrl;
                           rng.InlineShapes.AddPicture(imageProfPic, ref missing, ref missing, ref missing);
                           rng.InsertBefore(newLine.ToString());
                           rng.InsertAfter(newLine.ToString());
                           wordApp.Visible = true;
               ref missing, ref missing,ref missing);



                       }
                       catch (Exception)
                       {
                           throw;
                       }

                       finally
                       {

                           myDoc.Save();
                           myDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
                           wordApp.Quit(ref doNotSaveChanges, ref missing, ref missing);





                           System.IO.Stream iStream = null;

                           // Buffer to read 10K bytes in chunk:
                           byte[] buffer = new Byte[10000];

                           // Length of the file:
                           int length;

                           // Total bytes to read:
                           long dataToRead;

                           // Identify the file to download including its path.
                           string filepath = fs.ToString();
                           // Identify the file name.
                           string filename = System.IO.Path.GetFileName(filepath);

                           try
                           {

                               iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                                                                  System.IO.FileAccess.Read, System.IO.FileShare.Read);

                               dataToRead = iStream.Length;

                               Response.ContentType = "application/octet-stream";
                               Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

                               while (dataToRead > 0)
                               {

                                   if (Response.IsClientConnected)
                                   {

                                       length = iStream.Read(buffer, 0, 10000);


                                       Response.OutputStream.Write(buffer, 0, length);

                                       Response.Flush();

                                       buffer = new Byte[10000];
                                       dataToRead = dataToRead - length;
                                   }
                                   else
                                   {
                                       dataToRead = -1;
                                   }
                               }
                           }
                           catch (Exception ex)
                           {
                               Response.Write("Error : " + ex.Message);
                           }
                           finally
                           {
                               if (iStream != null)
                               {

                                   iStream.Close();

                               }
                               Response.Close();

                           }


                       }
                   }
               }


           }
       }
   }
Posted
Comments
Mayur Panchal 17-May-13 3:10am    
Is it winForms application or web(ASP.net) ?
Kurac1 17-May-13 3:21am    
web asp.net

1 solution

I have not much idea, how to implement this in ASP.net.
But i have converted word to PDF in one of my windows application.
For that i need "Save and XPS and PDF " add in : Microsoft Save as PDF or XPS [Download] [^] and below is the code to conver Word to PDF,

C#
using Word = Microsoft.Office.Interop.Word;

private bool Convert(string sourcePath, string targetPath)
        {
            Word.WdExportFormat targetFileType == Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            bool result;
            object paramMissing = Type.Missing;            
            Word.Application wordApplication = new Word.Application();
            Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;
                Word.WdExportFormat paramExportFormat = targetFileType;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor =
                Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks =
                Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;
                wordDocument = wordApplication.Documents.Open(
                                       ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                       ref paramMissing, ref paramMissing, ref paramMissing,
                                       ref paramMissing, ref paramMissing, ref paramMissing,
                                       ref paramMissing, ref paramMissing, ref paramMissing,
                                       ref paramMissing, ref paramMissing, ref paramMissing,
                                       ref paramMissing);

                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                    paramExportFormat, paramOpenAfterExport,
                    paramExportOptimizeFor, paramExportRange, paramStartPage,
                    paramEndPage, paramExportItem, paramIncludeDocProps,
                    paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                    paramBitmapMissingFonts, paramUseISO19005_1,
                    ref paramMissing);
                result = true;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }


sourcePath : path of word file
targetPath : path of pdf file with name and extension. (i.e. D:\\Output.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