首页 > 编程 > C# > 正文

C#实现HTML转WORD及WORD转PDF的方法

2019-10-29 21:37:45
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C#实现HTML转WORD及WORD转PDF的方法,涉及C#实现HTML、WORD及PDF等文件格式转换的相关技巧,需要的朋友可以参考下

本文实例讲述了C#实现HTML转WORD及WORD转PDF的方法。分享给大家供大家参考。具体如下:

功能:实现HTML转WORD,WORD转PDF

具体代码如下:

 

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.ComponentModel; 
  4. using System.Data; 
  5. using System.Drawing; 
  6. using System.Text; 
  7. using System.Windows.Forms; 
  8. using Word = Microsoft.Office.Interop.Word; 
  9. using oWord = Microsoft.Office.Interop.Word; 
  10. using System.Reflection; 
  11. using System.Configuration; 
  12. using System.Web; 
  13. using System.Web.Security; 
  14. using System.Web.UI; 
  15. using System.Web.UI.WebControls; 
  16. using System.Web.UI.WebControls.WebParts; 
  17. using System.Web.UI.HtmlControls; 
  18. using Microsoft.Office.Core; 
  19. using System.Text.RegularExpressions; 
  20. namespace WindowsApplication2 
  21. public partial class Form1 : Form 
  22. public Form1() 
  23. InitializeComponent(); 
  24. private void button1_Click(object sender, EventArgs e) 
  25. object oMissing = System.Reflection.Missing.Value; 
  26. object oEndOfDoc = "//endofdoc"/* /endofdoc is a predefined bookmark */ 
  27. //Start Word and create a new document. 
  28. Word._Application oWord; 
  29. Word._Document oDoc; 
  30. oWord = new Word.Application(); 
  31. oWord.Visible = true
  32. oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, 
  33. ref oMissing, ref oMissing); 
  34. //Insert a paragraph at the beginning of the document. 
  35. Word.Paragraph oPara1; 
  36. oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); 
  37. oPara1.Range.Text = "Heading 1"
  38. oPara1.Range.Font.Bold = 1; 
  39. oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. 
  40. oPara1.Range.InsertParagraphAfter(); 
  41. //Insert a paragraph at the end of the document. 
  42. Word.Paragraph oPara2; 
  43. object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  44. oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); 
  45. oPara2.Range.Text = "Heading 2"
  46. oPara2.Format.SpaceAfter = 6; 
  47. oPara2.Range.InsertParagraphAfter(); 
  48. //Insert another paragraph. 
  49. Word.Paragraph oPara3; 
  50. oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  51. oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); 
  52. oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"
  53. oPara3.Range.Font.Bold = 0; 
  54. oPara3.Format.SpaceAfter = 24; 
  55. oPara3.Range.InsertParagraphAfter(); 
  56. //Insert a 3 x 5 table, fill it with data, and make the first row 
  57. //bold and italic. 
  58. Word.Table oTable; 
  59. Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  60. oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); 
  61. oTable.Range.ParagraphFormat.SpaceAfter = 6; 
  62. int r, c; 
  63. string strText; 
  64. for (r = 1; r <= 3; r++) 
  65. for (c = 1; c <= 5; c++) 
  66. strText = "r" + r + "c" + c; 
  67. oTable.Cell(r, c).Range.Text = strText; 
  68. oTable.Rows[1].Range.Font.Bold = 1; 
  69. oTable.Rows[1].Range.Font.Italic = 1; 
  70. //Add some text after the table. 
  71. Word.Paragraph oPara4; 
  72. oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  73. oPara4 = oDoc.Content.Paragraphs.Add(ref oRng); 
  74. oPara4.Range.InsertParagraphBefore(); 
  75. oPara4.Range.Text = "And here's another table:"
  76. oPara4.Format.SpaceAfter = 24; 
  77. oPara4.Range.InsertParagraphAfter(); 
  78. //Insert a 5 x 2 table, fill it with data, and change the column widths. 
  79. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  80. oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing); 
  81. oTable.Range.ParagraphFormat.SpaceAfter = 6; 
  82. for (r = 1; r <= 5; r++) 
  83. for (c = 1; c <= 2; c++) 
  84. strText = "r" + r + "c" + c; 
  85. oTable.Cell(r, c).Range.Text = strText; 
  86. oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2 
  87. oTable.Columns[2].Width = oWord.InchesToPoints(3); 
  88. //Keep inserting text. When you get to 7 inches from top of the 
  89. //document, insert a hard page break. 
  90. object oPos; 
  91. double dPos = oWord.InchesToPoints(7); 
  92. oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter(); 
  93. do 
  94. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  95. wrdRng.ParagraphFormat.SpaceAfter = 6; 
  96. wrdRng.InsertAfter("A line of text"); 
  97. wrdRng.InsertParagraphAfter(); 
  98. oPos = wrdRng.get_Information 
  99. (Word.WdInformation.wdVerticalPositionRelativeToPage); 
  100. while (dPos >= Convert.ToDouble(oPos)); 
  101. object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd; 
  102. object oPageBreak = Word.WdBreakType.wdPageBreak; 
  103. wrdRng.Collapse(ref oCollapseEnd); 
  104. wrdRng.InsertBreak(ref oPageBreak); 
  105. wrdRng.Collapse(ref oCollapseEnd); 
  106. wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); 
  107. wrdRng.InsertParagraphAfter(); 
  108. //Insert a chart. 
  109. Word.InlineShape oShape; 
  110. object oClassType = "MSGraph.Chart.8"
  111. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  112. oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, 
  113. ref oMissing, ref oMissing, ref oMissing, 
  114. ref oMissing, ref oMissing, ref oMissing); 
  115. //Demonstrate use of late bound oChart and oChartApp objects to 
  116. //manipulate the chart object with MSGraph. 
  117. object oChart; 
  118. object oChartApp; 
  119. oChart = oShape.OLEFormat.Object; 
  120. oChartApp = oChart.GetType().InvokeMember("Application"
  121. BindingFlags.GetProperty, null, oChart, null); 
  122. //Change the chart type to Line. 
  123. object[] Parameters = new Object[1]; 
  124. Parameters[0] = 4; //xlLine = 4 
  125. oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, 
  126. null, oChart, Parameters); 
  127. //Update the chart image and quit MSGraph. 
  128. oChartApp.GetType().InvokeMember("Update"
  129. BindingFlags.InvokeMethod, null, oChartApp, null); 
  130. oChartApp.GetType().InvokeMember("Quit"
  131. BindingFlags.InvokeMethod, null, oChartApp, null); 
  132. //... If desired, you can proceed from here using the Microsoft Graph  
  133. //Object model on the oChart and oChartApp objects to make additional 
  134. //changes to the chart. 
  135. //Set the width of the chart. 
  136. oShape.Width = oWord.InchesToPoints(6.25f); 
  137. oShape.Height = oWord.InchesToPoints(3.57f); 
  138. //Add text after the chart. 
  139. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 
  140. wrdRng.InsertParagraphAfter(); 
  141. wrdRng.InsertAfter("THE END."); 
  142. //Close this form. 
  143. this.Close(); 
  144. private void button2_Click(object sender, EventArgs e) 
  145. string s = ""
  146. if (openFileDialog1.ShowDialog() == DialogResult.OK) 
  147. s = openFileDialog1.FileName; 
  148. else 
  149. return
  150. // 在此处放置用户代码以初始化页面 
  151. Word.ApplicationClass word = new Word.ApplicationClass(); 
  152. Type wordType = word.GetType(); 
  153. Word.Documents docs = word.Documents; 
  154. // 打开文件 
  155. Type docsType = docs.GetType(); 
  156. object fileName = s; 
  157. Word.Document doc = (Word.Document)docsType.InvokeMember("Open"
  158. System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, falsefalse }); 
  159. // 转换格式,另存为 
  160. Type docType = doc.GetType(); 
  161. object saveFileName = "d://Reports//aaa.doc"
  162. //下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成: 
  163. /* 
  164. docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, 
  165. null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML}); 
  166. */ 
  167. ///其它格式: 
  168. ///wdFormatHTML 
  169. ///wdFormatDocument 
  170. ///wdFormatDOSText 
  171. ///wdFormatDOSTextLineBreaks 
  172. ///wdFormatEncodedText 
  173. ///wdFormatRTF 
  174. ///wdFormatTemplate 
  175. ///wdFormatText 
  176. ///wdFormatTextLineBreaks 
  177. ///wdFormatUnicodeText 
  178. docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, 
  179. null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatDocument }); 
  180. // 退出 Word 
  181. wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, 
  182. null, word, null); 
  183. private void WordConvert(string s) 
  184. oWord.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); 
  185. Type wordType = word.GetType(); 
  186. //打开WORD文档 
  187. /*对应脚本中的 
  188. var word = new ActiveXObject("Word.Application"); 
  189. var doc = word.Documents.Open(docfile); 
  190. */ 
  191. oWord.Documents docs = word.Documents; 
  192. Type docsType = docs.GetType(); 
  193. object objDocName =s; 
  194. oWord.Document doc = (oWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, truetrue }); 
  195. //打印输出到指定文件 
  196. //你可以使用 doc.PrintOut();方法,次方法调用中的参数设置较繁琐,建议使用 Type.InvokeMember 来调用时可以不用将PrintOut的参数设置全,只设置4个主要参数 
  197. Type docType = doc.GetType(); 
  198. object printFileName = @"c:/aaa.ps"
  199. docType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { falsefalse, oWord.WdPrintOutRange.wdPrintAllDocument, printFileName }); 
  200. //new object[]{false,false,oWord.WdPrintOutRange.wdPrintAllDocument,printFileName} 
  201. //对应脚本中的word.PrintOut(false, false, 0, psfile);的参数 
  202. //退出WORD 
  203. //对应脚本中的word.Quit(); 
  204. wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); 
  205. object o1 = "c://aaa.ps"
  206. object o2 = "c://aaa.pdf"
  207. object o3 = ""
  208. //引用将PS转换成PDF的对象 
  209. //try catch之间对应的是脚本中的 PDF.FileToPDF(psfile,pdffile,""); //你可以使用 pdfConvert.FileToPDF("c://test.ps","c://test.pdf","");这样的转换方法,本人只是为了保持与WORD相同的调用方式 
  210. try 
  211. ACRODISTXLib.PdfDistillerClass pdf = new ACRODISTXLib.PdfDistillerClass(); 
  212. Type pdfType = pdf.GetType(); 
  213. pdfType.InvokeMember("FileToPDF", System.Reflection.BindingFlags.InvokeMethod, null, pdf, new object[] { o1, o2, o3 }); 
  214. pdf = null
  215. catch { } //读者自己补写错误处理 
  216. //为防止本方法调用多次时发生错误,必须停止acrodist.exe进程 
  217. foreach (System.Diagnostics .Process proc in System.Diagnostics.Process.GetProcesses()) 
  218. int begpos; 
  219. int endpos; 
  220. string sProcName = proc.ToString(); 
  221. begpos = sProcName.IndexOf("(") + 1; 
  222. endpos = sProcName.IndexOf(")"); 
  223. sProcName = sProcName.Substring(begpos, endpos - begpos); 
  224. if (sProcName.ToLower().CompareTo("acrodist") == 0) 
  225. try 
  226. proc.Kill(); //停止进程 
  227. catch { } //读者自己补写错误处理 
  228. break
  229. private void button3_Click(object sender, EventArgs e) 
  230. if (openFileDialog1.ShowDialog() == DialogResult.OK) 
  231. string s = openFileDialog1.FileName; 
  232. WordConvert(s); 
  233. //getnextcode 
  234. private void button4_Click(object sender, EventArgs e) 
  235. WorkCell myWorkCell = new WorkCell(textBox2.Text,textBox1.Text); 
  236. textBox3.Text = myWorkCell.GetNextCode(); 
  237. public class WorkCell 
  238. private string workCellCode; 
  239. private string parentCellCode; 
  240. private string commonCode; 
  241. private char[] code; 
  242. private char[] pCode; 
  243. private char[] standCode; 
  244. private string s; 
  245. public WorkCell( string mycode,string parentcode) 
  246. workCellCode = mycode; 
  247. parentCellCode = parentcode; 
  248. standCode = new char[] { '1''2''3''4''5''6''7''8''9''A''B''C''D''E''F''G''H''I''J''K''L''M''N''O''P''Q''R''W''T''U''V''W''X''Y''Z' }; 
  249. commonCode = Regex.Replace(parentCellCode,@"0+",""); 
  250. code = workCellCode.Substring(commonCode.Length).ToCharArray(); 
  251. public string WorkCellCode 
  252. set 
  253. workCellCode = value; 
  254. get 
  255. return workCellCode; 
  256. public string ParentCellCode 
  257. {  
  258. set 
  259. workCellCode = value; 
  260. get 
  261. return workCellCode; 
  262. public string GetNextCode() 
  263. string s=""
  264. if (code.Length > 0) 
  265. int i = 0; 
  266. for (i = code.Length - 1; i >= 0; i--) 
  267. if (code[i] != '0'
  268. GetNextChar(i); 
  269. break
  270. for(i=0;i<code.Length;i++) 
  271. s+=code[i].ToString(); 
  272. return commonCode + s; 
  273. else 
  274. return "null"
  275. //设置code中的下一个代码,从右边起,找到第一个非0字符,将其按标准代码自加1,溢出则进位 
  276. private char GetNextChar(int j) 
  277. int i = -1; 
  278. int flag = 0; 
  279. for (i = 0; i < standCode.Length; i++) 
  280. if (code[j] == standCode[i]) 
  281. flag = 1; 
  282. break
  283. //MessageBox.Show(code[j].ToString()+" "+standCode[i].ToString()+" "+i.ToString()); 
  284. if (i >= standCode.Length-1 || flag==0) 
  285. code[j] = standCode[0]; 
  286. if (j > 0) 
  287. code[j - 1] = GetNextChar(j - 1); 
  288. else 
  289. code[j] = standCode[i + 1]; 
  290. return code[j]; 

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表