c html转换成word,C#实现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

{

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#程序设计有所帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/574814.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

bootstrap下拉框分页_【Bootstrap】 bootstrap-select2下拉菜单插件

这次开发了个小TRS系统&#xff0c;虽然是很小&#xff0c;但是作为初心者&#xff0c;第一次用到了很多看起来洋气使用起来有相对简单的各种前端(主要是和bootstrap配合使用)组件。包括bootstrap-select2&#xff0c;bootstrap-datetimepicker&#xff0c;bootstrap-fileinput…

Java-eclipse快捷键及设置

CtrlD: 删除当前行 CtrlAlt↓ 复制当前行到下一行(复制增加) CtrlAlt↑ 复制当前行到上一行(复制增加) Alt↓ 当前行和下面一行交互位置(特别实用,可以省去先剪切,再粘贴了) Alt↑ 当前行和上面一行交互位置(同上) Alt← 前一个编辑的页面 Alt→ 下一个编辑的页面(当然是针对上…

html 网页主题设置吗,如何使用css样式对html页面进行背景设置呢?

摘要:下文讲述css样式对html页面的背景色、背景图片进行相关设置的方法分享&#xff0c;如下所示:在html中&#xff0c;定义元素的背景信息&#xff0c;可以采用以下css属性&#xff0c;如下所示:css属性功能background在此属性中,我们将所有的背景设置都放入此属性值中backgro…

redis 缓存 @class: 会有 $hibernateproxy_微信亿级在线点赞系统,用Redis如何实现?

点赞功能大家都不会陌生&#xff0c;像微信这样的社交产品中都有&#xff0c;但别看功能小&#xff0c;想要做好需要考虑的东西还挺多的&#xff0c;如海量数据的分布式存储、分布式缓存、多 IDC 的数据一致性、访问路由到机房的算法等等。图片来 Pexels本文介绍大型社交平台点…

Xcode怎样调整模拟器大小

快捷键&#xff1a; Command 1&#xff1a;显示100%大小 Command 2&#xff1a;显示50%大小&#xff08;默认&#xff09;转载于:https://www.cnblogs.com/xiaofeng6636/p/4311753.html

查询hive表_大数据中Hive与HBase的区别与联系

二者区别Hive&#xff1a;Hive是基于Hadoop的一个数据仓库工具&#xff0c;可以将结构化的数据文件映射为一张数据库表&#xff0c;并提供简单的sql查询功能。Hive本身不存储和计算数据&#xff0c;它完全依赖于HDFS和MapReduce&#xff0c;Hive中的表纯逻辑。hive需要用到hdfs…

查询使用NoLock

当我们在操作数据库的时候&#xff0c;无论是查询还是修改数据库的操作我们都习惯使用using(var dbnew XXXDB()){}&#xff0c;但是如果仅仅是做查询&#xff0c;最好是使用NoLock&#xff0c;因为NoLock使用的是共享锁&#xff0c;可以减少死锁发生的机率。 从上图中代码可以看…

端午粽香html5游戏,《快乐端午粽飘香》亲子活动教案

《快乐端午粽飘香》亲子活动教案过端午节是我国两千多年来的习惯&#xff0c;为了让幼儿更好地了解端午节&#xff0c;感受端午节丰富的文化内涵&#xff0c;激发初步的爱国主义情感&#xff0c;丰富生活经验&#xff0c;应届毕业生考试网小编特意为大家整理了《快乐端午粽飘香…

d3js绘制y坐标轴_【ggplot2】 设置坐标轴

基本箱线图library(ggplot2)bp ggplot(PlantGrowth, aes(xgroup, yweight)) geom_boxplot()bp反转 x轴 与 y轴bp coord_flip()离散型数据的坐标轴改变坐标轴中各项目的顺序 > 特别注意, 离散数据的坐标轴中数据做为 factor 变量处理,他的位置取决于 level的顺序# 手动设置…

html5点击视频跳转,javascript – 播放后重定向html5视频

我有一个html 5视频,我删除了控制按钮并添加了一个js代码,以便用户在点击视频时播放视频.我需要做的是绑定一个额外的脚本,在播放视频后重定向页面而不重新加载页面.下面是我的js代码.function play(){var video document.getElementById(video);video.addEventListener(click…

setInterval

定义和用法&#xff1a; setInterval() 方法可按照指定的周期&#xff08;以毫秒计&#xff09;来调用函数或计算表达式。 setInterval() 方法会不停地调用函数&#xff0c;直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法…

Android working with volley

http://www.cnblogs.com/a284628487/p/4073771.html转载于:https://www.cnblogs.com/soaringEveryday/articles/4320262.html

maya藤蔓插件_MAYA快速打造藤蔓生长的路径动画教程

第一页&#xff1a;MAYA快速打造藤蔓生长的路径动画教程第二页&#xff1a;MAYA快速打造藤蔓生长的路径动画教程第三页&#xff1a;MAYA快速打造藤蔓生长的路径动画教程我相信很多人大部分时间在学习高级技巧&#xff0c;诸如zb mud啦&#xff0c;GI FG啦&#xff0c;motionBui…

移动端拖拽排序 html,移动端拖拽排序

var drag {bindDragEvent: function (isF) {var father document.getElementById("public_theme_list");//父容器var btns father.getElementsByClassName("public-drag-btn");//事件源对象var items father.getElementsByClassName("item")…

pyqt5 qscrollarea到达_pyqt5 QScrollArea设置在自定义侧(任何位置)

本例设置为垂直左侧scroll主要思想是利用一个长度为0的mid_frame&#xff0c;高度为待设置qwidget的高度&#xff0c;用mid_frame的moveEvent事件驱动qwidget的move我项目的效果图&#xff1a;代码及注释from PyQt5.Qt import *from sys import argv# 主窗口class Main(QMainWi…

html页面判断是否登录,egg(103)--egg之定义公共的中间件判断用户是否登录以及去结算页面制作...

判断用户是否登录中间件app/middleware/userauth.jsmodule.exports (options, app) > {return async function init(ctx, next) {//判断前台用户是否登录 如果登录可以进入 ( 去结算 用户中心) 如果没有登录直接跳转到登录var userinfo ctx.service.cookies.get(userinfo)…

3月初的日记:网站工作记录

一直在备考。考一个关于自己本身工作的资格证。也一直在忙碌中&#xff0c;三个项目的并驾齐驱。 可以说&#xff0c;我也很忙。 东北今天下了很大雪&#xff0c;厚厚的&#xff0c;踩上去咯吱咯吱的响&#xff0c;这样的安逸更容易使得心静下来。 但是&#xff0c;其实我是焦虑…

电子科技大学研究生计算机与科学,2019年电子科技大学计算机科学与工程学院考研复试分数线...

据电子科技大学研究生院消息&#xff0c;2019年电子科技大学计算机科学与工程学院考研复试分数线及调剂信息已出&#xff0c;详情如下&#xff1a;专业第一单元第二单元第三单元第四单元总分调剂调剂开放时间调剂结束时间公开招考人数081200计算机科学与技术50458090340不接收2…

debian 重复执行sh_debian 脚本启动方式

同所有的Unix一样,Debian启动时要执行init程序.init的配置文件(/etc/inittab)中指定的第一个执行脚本应该是/etc/init.d/rcS.该脚本执行/etc/rcS.d/目录中各脚本的扩展名指定或衍生进程完成诸如检查并挂载文件系,装载内核模块,启动网络服务,设定时钟等系统初始化工作.接着,为了…

(None resource)-Binary system

Description 给定一个范围[a,b] (0<a<b<10^18) 求出该范围内二进制中1的个数最多的数&#xff0c;如果存在多个答案&#xff0c;输出最小的那个数 Input 输入数据有多组&#xff0c;每组数据输入两个整数a&#xff0c;b&#xff0c;表示区间[a, b]。 Output 输出该区…