欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-09 19:17:52
本文实例讲述了c#实现html转word及word转pdf的方法。分享给大家供大家参考。具体如下: 功能:实现html转word,word转pdf 具体代码如下:...

本文实例讲述了c#实现html转word及word转pdf的方法。分享给大家供大家参考。具体如下:

功能:实现html转word,word转pdf

具体代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using word = microsoft.office.interop.word;
using oword = microsoft.office.interop.word;
using system.reflection;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using microsoft.office.core;
using system.text.regularexpressions;
namespace windowsapplication2
{
 public partial class form1 : form
 {
  public form1()
  {
   initializecomponent();
  }
  private void button1_click(object sender, eventargs e)
  {
   object omissing = system.reflection.missing.value;
   object oendofdoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
   //start word and create a new document.
   word._application oword;
   word._document odoc;
   oword = new word.application();
   oword.visible = true;
   odoc = oword.documents.add(ref omissing, ref omissing,
    ref omissing, ref omissing);
   //insert a paragraph at the beginning of the document.
   word.paragraph opara1;
   opara1 = odoc.content.paragraphs.add(ref omissing);
   opara1.range.text = "heading 1";
   opara1.range.font.bold = 1;
   opara1.format.spaceafter = 24; //24 pt spacing after paragraph.
   opara1.range.insertparagraphafter();
   //insert a paragraph at the end of the document.
   word.paragraph opara2;
   object orng = odoc.bookmarks.get_item(ref oendofdoc).range;
   opara2 = odoc.content.paragraphs.add(ref orng);
   opara2.range.text = "heading 2";
   opara2.format.spaceafter = 6;
   opara2.range.insertparagraphafter();
   //insert another paragraph.
   word.paragraph opara3;
   orng = odoc.bookmarks.get_item(ref oendofdoc).range;
   opara3 = odoc.content.paragraphs.add(ref orng);
   opara3.range.text = "this is a sentence of normal text. now here is a table:";
   opara3.range.font.bold = 0;
   opara3.format.spaceafter = 24;
   opara3.range.insertparagraphafter();
   //insert a 3 x 5 table, fill it with data, and make the first row
   //bold and italic.
   word.table otable;
   word.range wrdrng = odoc.bookmarks.get_item(ref oendofdoc).range;
   otable = odoc.tables.add(wrdrng, 3, 5, ref omissing, ref omissing);
   otable.range.paragraphformat.spaceafter = 6;
   int r, c;
   string strtext;
   for (r = 1; r <= 3; r++)
    for (c = 1; c <= 5; c++)
    {
     strtext = "r" + r + "c" + c;
     otable.cell(r, c).range.text = strtext;
    }
   otable.rows[1].range.font.bold = 1;
   otable.rows[1].range.font.italic = 1;
   //add some text after the table.
   word.paragraph opara4;
   orng = odoc.bookmarks.get_item(ref oendofdoc).range;
   opara4 = odoc.content.paragraphs.add(ref orng);
   opara4.range.insertparagraphbefore();
   opara4.range.text = "and here's another table:";
   opara4.format.spaceafter = 24;
   opara4.range.insertparagraphafter();
   //insert a 5 x 2 table, fill it with data, and change the column widths.
   wrdrng = odoc.bookmarks.get_item(ref oendofdoc).range;
   otable = odoc.tables.add(wrdrng, 5, 2, ref omissing, ref omissing);
   otable.range.paragraphformat.spaceafter = 6;
   for (r = 1; r <= 5; r++)
    for (c = 1; c <= 2; c++)
    {
     strtext = "r" + r + "c" + c;
     otable.cell(r, c).range.text = strtext;
    }
   otable.columns[1].width = oword.inchestopoints(2); //change width of columns 1 & 2
   otable.columns[2].width = oword.inchestopoints(3);
   //keep inserting text. when you get to 7 inches from top of the
   //document, insert a hard page break.
   object opos;
   double dpos = oword.inchestopoints(7);
   odoc.bookmarks.get_item(ref oendofdoc).range.insertparagraphafter();
   do
   {
    wrdrng = odoc.bookmarks.get_item(ref oendofdoc).range;
    wrdrng.paragraphformat.spaceafter = 6;
    wrdrng.insertafter("a line of text");
    wrdrng.insertparagraphafter();
    opos = wrdrng.get_information
        (word.wdinformation.wdverticalpositionrelativetopage);
   }
   while (dpos >= convert.todouble(opos));
   object ocollapseend = word.wdcollapsedirection.wdcollapseend;
   object opagebreak = word.wdbreaktype.wdpagebreak;
   wrdrng.collapse(ref ocollapseend);
   wrdrng.insertbreak(ref opagebreak);
   wrdrng.collapse(ref ocollapseend);
   wrdrng.insertafter("we're now on page 2. here's my chart:");
   wrdrng.insertparagraphafter();
   //insert a chart.
   word.inlineshape oshape;
   object oclasstype = "msgraph.chart.8";
   wrdrng = odoc.bookmarks.get_item(ref oendofdoc).range;
   oshape = wrdrng.inlineshapes.addoleobject(ref oclasstype, ref omissing,
    ref omissing, ref omissing, ref omissing,
    ref omissing, ref omissing, ref omissing);
   //demonstrate use of late bound ochart and ochartapp objects to
   //manipulate the chart object with msgraph.
   object ochart;
   object ochartapp;
   ochart = oshape.oleformat.object;
   ochartapp = ochart.gettype().invokemember("application",
    bindingflags.getproperty, null, ochart, null);
   //change the chart type to line.
   object[] parameters = new object[1];
   parameters[0] = 4; //xlline = 4
   ochart.gettype().invokemember("charttype", bindingflags.setproperty,
    null, ochart, parameters);
   //update the chart image and quit msgraph.
   ochartapp.gettype().invokemember("update",
    bindingflags.invokemethod, null, ochartapp, null);
   ochartapp.gettype().invokemember("quit",
    bindingflags.invokemethod, null, ochartapp, null);
   //... if desired, you can proceed from here using the microsoft graph 
   //object model on the ochart and ochartapp objects to make additional
   //changes to the chart.
   //set the width of the chart.
   oshape.width = oword.inchestopoints(6.25f);
   oshape.height = oword.inchestopoints(3.57f);
   //add text after the chart.
   wrdrng = odoc.bookmarks.get_item(ref oendofdoc).range;
   wrdrng.insertparagraphafter();
   wrdrng.insertafter("the end.");
   //close this form.
   this.close();
  }
  private void button2_click(object sender, eventargs e)
  {
   string s = "";
   if (openfiledialog1.showdialog() == dialogresult.ok)
   {
    s = openfiledialog1.filename;
   }
   else
   {
    return;
   }
   // 在此处放置用户代码以初始化页面
   word.applicationclass word = new word.applicationclass();
   type wordtype = word.gettype();
   word.documents docs = word.documents;
   // 打开文件
   type docstype = docs.gettype();
   object filename = s;
   word.document doc = (word.document)docstype.invokemember("open",
   system.reflection.bindingflags.invokemethod, null, docs, new object[] { filename, false, false });
   // 转换格式,另存为
   type doctype = doc.gettype();
   object savefilename = "d:\\reports\\aaa.doc";
   //下面是microsoft word 9 object library的写法,如果是10,可能写成:
   /*
   doctype.invokemember("saveas", system.reflection.bindingflags.invokemethod,
    null, doc, new object[]{savefilename, word.wdsaveformat.wdformatfilteredhtml});
   */
   ///其它格式:
   ///wdformathtml
   ///wdformatdocument
   ///wdformatdostext
   ///wdformatdostextlinebreaks
   ///wdformatencodedtext
   ///wdformatrtf
   ///wdformattemplate
   ///wdformattext
   ///wdformattextlinebreaks
   ///wdformatunicodetext
   doctype.invokemember("saveas", system.reflection.bindingflags.invokemethod,
    null, doc, new object[] { savefilename, word.wdsaveformat.wdformatdocument });
   // 退出 word
   wordtype.invokemember("quit", system.reflection.bindingflags.invokemethod,
    null, word, null);
  }
  private void wordconvert(string s)
  {
   oword.applicationclass word = new microsoft.office.interop.word.applicationclass();
   type wordtype = word.gettype();
   //打开word文档
   /*对应脚本中的
    var word = new activexobject("word.application");
    var doc = word.documents.open(docfile);
   */
   oword.documents docs = word.documents;
   type docstype = docs.gettype();
   object objdocname =s;
   oword.document doc = (oword.document)docstype.invokemember("open", system.reflection.bindingflags.invokemethod, null, docs, new object[] { objdocname, true, true });
   //打印输出到指定文件
   //你可以使用 doc.printout();方法,次方法调用中的参数设置较繁琐,建议使用 type.invokemember 来调用时可以不用将printout的参数设置全,只设置4个主要参数
   type doctype = doc.gettype();
   object printfilename = @"c:\aaa.ps";
   doctype.invokemember("printout", system.reflection.bindingflags.invokemethod, null, doc, new object[] { false, false, oword.wdprintoutrange.wdprintalldocument, printfilename });
   //new object[]{false,false,oword.wdprintoutrange.wdprintalldocument,printfilename}
   //对应脚本中的word.printout(false, false, 0, psfile);的参数
   //退出word
   //对应脚本中的word.quit();
   wordtype.invokemember("quit", system.reflection.bindingflags.invokemethod, null, word, null);
   object o1 = "c:\\aaa.ps";
   object o2 = "c:\\aaa.pdf";
   object o3 = "";
   //引用将ps转换成pdf的对象
   //try catch之间对应的是脚本中的 pdf.filetopdf(psfile,pdffile,"");  //你可以使用 pdfconvert.filetopdf("c:\\test.ps","c:\\test.pdf","");这样的转换方法,本人只是为了保持与word相同的调用方式
   try
   {
    acrodistxlib.pdfdistillerclass pdf = new acrodistxlib.pdfdistillerclass();
    type pdftype = pdf.gettype();
    pdftype.invokemember("filetopdf", system.reflection.bindingflags.invokemethod, null, pdf, new object[] { o1, o2, o3 });
    pdf = null;
   }
   catch { } //读者自己补写错误处理
   //为防止本方法调用多次时发生错误,必须停止acrodist.exe进程
   foreach (system.diagnostics .process proc in system.diagnostics.process.getprocesses())
   {
    int begpos;
    int endpos;
    string sprocname = proc.tostring();
    begpos = sprocname.indexof("(") + 1;
    endpos = sprocname.indexof(")");
    sprocname = sprocname.substring(begpos, endpos - begpos);
    if (sprocname.tolower().compareto("acrodist") == 0)
    {
     try
     {
      proc.kill(); //停止进程
     }
     catch { } //读者自己补写错误处理
     break;
    }
   }
  }
  private void button3_click(object sender, eventargs e)
  {
   if (openfiledialog1.showdialog() == dialogresult.ok)
   {
    string s = openfiledialog1.filename;
    wordconvert(s);
   }
  }
  //getnextcode
  private void button4_click(object sender, eventargs e)
  {
   workcell myworkcell = new workcell(textbox2.text,textbox1.text);
   textbox3.text = myworkcell.getnextcode();
  }
 }
 public class workcell
 {
  private string workcellcode;
  private string parentcellcode;
  private string commoncode;
  private char[] code;
  private char[] pcode;
  private char[] standcode;
  private string s;
  public workcell( string mycode,string parentcode)
  {
   workcellcode = mycode;
   parentcellcode = parentcode;
   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' };
   commoncode = regex.replace(parentcellcode,@"0+","");
   code = workcellcode.substring(commoncode.length).tochararray();
  }
  public string workcellcode
  {
   set
   {
    workcellcode = value;
   }
   get
   {
    return workcellcode;
   }
  }
  public string parentcellcode
  { 
   set
   {
    workcellcode = value;
   }
   get
   {
    return workcellcode;
   }
  }
  public string getnextcode()
  {
   string s="";
   if (code.length > 0)
   {
    int i = 0;
    for (i = code.length - 1; i >= 0; i--)
    {
     if (code[i] != '0')
     {
      getnextchar(i);
      break;
     }
    }
    for(i=0;i<code.length;i++)
    {
     s+=code[i].tostring();
    }
    return commoncode + s;
   }
   else
   {
    return "null";
   }
  }
  //设置code中的下一个代码,从右边起,找到第一个非0字符,将其按标准代码自加1,溢出则进位
  private char getnextchar(int j)
  {
   int i = -1;
   int flag = 0;
   for (i = 0; i < standcode.length; i++)
   {
    if (code[j] == standcode[i])
    {
     flag = 1;
     break;
    }
   }
   //messagebox.show(code[j].tostring()+" "+standcode[i].tostring()+" "+i.tostring());
   if (i >= standcode.length-1 || flag==0)
   {
    code[j] = standcode[0];
    if (j > 0)
     code[j - 1] = getnextchar(j - 1);
   }
   else
   {
    code[j] = standcode[i + 1];
   }
   return code[j];
  }
 }
}

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