输出位html是对的,输出到pdf和pdf转word格式保持不变就这样

C#实现HTML转WORD及WORD转PDF的方法
转载 &更新时间:日 16:57:05 & 作者:清清飞扬
这篇文章主要介绍了C#实现HTML转WORD及WORD转PDF的方法,涉及C#实现HTML、WORD及PDF等文件格式转换的相关技巧,需要的朋友可以参考下
本文实例讲述了C#实现HTML转WORD及WORD转PDF的方法。分享给大家供大家参考。具体如下:
功能:实现HTML转WORD,WORD转PDF
具体代码如下:
using System.Collections.G
using System.ComponentM
using System.D
using System.D
using System.T
using System.Windows.F
using Word = Microsoft.Office.Interop.W
using oWord = Microsoft.Office.Interop.W
using System.R
using System.C
using System.W
using System.Web.S
using System.Web.UI;
using System.Web.UI.WebC
using System.Web.UI.WebControls.WebP
using System.Web.UI.HtmlC
using Microsoft.Office.C
using System.Text.RegularE
namespace WindowsApplication2
public partial class Form1 : Form
public Form1()
InitializeComponent();
private void button1_Click(object sender, EventArgs e)
object oMissing = System.Reflection.Missing.V
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
//Start Word and create a new document.
Word._Application oW
Word._Document oD
oWord = new Word.Application();
oWord.Visible =
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).R
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).R
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 oT
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).R
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
string strT
for (r = 1; r &= 3; r++)
for (c = 1; c &= 5; c++)
strText = "r" + r + "c" +
oTable.Cell(r, c).Range.Text = strT
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).R
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).R
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" +
oTable.Cell(r, c).Range.Text = strT
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.
double dPos = oWord.InchesToPoints(7);
oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).R
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.wdCollapseE
object oPageBreak = Word.WdBreakType.wdPageB
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 oS
object oClassType = "MSGraph.Chart.8";
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).R
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 oChartA
oChart = oShape.OLEFormat.O
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).R
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.FileN
// 在此处放置用户代码以初始化页面
Word.ApplicationClass word = new Word.ApplicationClass();
Type wordType = word.GetType();
Word.Documents docs = word.D
// 打开文件
Type docsType = docs.GetType();
object fileName =
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.D
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相同的调用方式
ACRODISTXLib.PdfDistillerClass pdf = new ACRODISTXLib.PdfDistillerClass();
Type pdfType = pdf.GetType();
pdfType.InvokeMember("FileToPDF", System.Reflection.BindingFlags.InvokeMethod, null, pdf, new object[] { o1, o2, o3 });
catch { } //读者自己补写错误处理
//为防止本方法调用多次时发生错误,必须停止acrodist.exe进程
foreach (System.Diagnostics .Process proc in System.Diagnostics.Process.GetProcesses())
string sProcName = proc.ToString();
begpos = sProcName.IndexOf("(") + 1;
endpos = sProcName.IndexOf(")");
sProcName = sProcName.Substring(begpos, endpos - begpos);
if (sProcName.ToLower().CompareTo("acrodist") == 0)
proc.Kill(); //停止进程
catch { } //读者自己补写错误处理
private void button3_Click(object sender, EventArgs e)
if (openFileDialog1.ShowDialog() == DialogResult.OK)
string s = openFileDialog1.FileN
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 workCellC
private string parentCellC
private string commonC
private char[]
private char[] pC
private char[] standC
public WorkCell( string mycode,string parentcode)
workCellCode =
parentCellCode =
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
workCellCode =
return workCellC
public string ParentCellCode
workCellCode =
return workCellC
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);
for(i=0;i&code.Li++)
s+=code[i].ToString();
return commonCode +
return "null";
//设置code中的下一个代码,从右边起,找到第一个非0字符,将其按标准代码自加1,溢出则进位
private char GetNextChar(int j)
int i = -1;
int flag = 0;
for (i = 0; i & standCode.L i++)
if (code[j] == standCode[i])
//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);
code[j] = standCode[i + 1];
return code[j];
希望本文所述对大家的C#程序设计有所帮助。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具椭圆C的中心在坐标轴原点O,焦点在y轴上,离心率为根号2/2,以短轴的一个端点与两焦点为顶点的三角形的面积为 - 搜问问吧 - 有问必答,有问题就来问吧!
更多登录方式:&&&&
椭圆C的中心在坐标轴原点O,焦点在y轴上,离心率为根号2/2,以短轴的一个端点与两焦点为顶点的三角形的面积为
椭圆C的中心在坐标轴原点O,焦点在y轴上,离心率为根号2/2,以短轴的一个端点与两焦点为顶点的三角形的面积为1/2.(1) 求椭圆C 的方程(2)喏过点P(0,m)存在直线L与椭圆C交于相异两点A,满足:向量AP=入向量PB且向量OA+入OB=4向量OP,求常数入的值和实数m的取值范围要过程
网友回答 (共2条)
解:(1)设椭圆的方程为: ,由题意知, ,且 ,解得: , .故椭圆C的方程为: .(2)由 得, ,∴ ,∴ , .当直线 与 轴不垂直时,设直线 的方程为: ,且与椭圆C的交点为 , ,由 得: ,∴ , , ,由 得 ,∴ , ,消去 得: ,即
, .当 时,上式不成立, ,∴ , 代入 ,即 ,得 恒成立,即 ,解得 ,∴ 或 .当直线 与 轴垂直时, 的方程为: 得 .综上所述: 的取值范围为 .
椭圆上的点到焦点的最短距离就是长轴端点到对应焦点的长度.由其等于1-e可知a=1 e=c/a c=√2/2b^2=a^2-c^2 b^2=1/2椭圆方程为2X^2+Y^2=1 ⑵设A(X1,Y1) B(X2,Y2)由向量AP=λ向量PB -X1=λX2 m-Y1=λ(Y2-m)由向量OA+λ向量OB=4向量OPX1+λX2=0Y1+λY2=4m联立以上4式λ=3即 X1^2=9X2^2 Y1^2=(4m-3Y2)^2 ①由椭圆方程2X1^2+Y1^2=1 2X2^2+Y2^2=1将①代入解得2m^2-3mY2+1=0Y2=(2m^2+1)/3m由于Y2∈[-1,1](2m^2+1)/3m∈[-1,1]解得m∈[-1,-1/2]∪[1/2,1]
更多相关问吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&下次自动登录
现在的位置:
& 综合 & 正文
IE下用JavaScript将HTML导出为Word、Pdf
最近升级公司内部系统发文章的功能,涉及到将文章内容导出为html、word、pdf,系统多用于IE环境下,并且公司电脑都预装了office,所以导出暂时采用客户端的方式。
页面基本结构:
&title&客户端导出测试&/title&
&script type="text/javascript"&
function exportHtml {
function exportWord() {
function exportPdf() {
&!-- toolbar --&
&button&导出HTML&/button&
&button&导出WORD&/button&
&button&导出PDF&/button&
&!-- content --&
&div id="content" style="border: 1px #000 solid"&
&h1&标题&/h1&
&font color="gray"&正文内容&/font&
可以复制下来在浏览器内看下效果,我们的目标是将content内的内容分别导出到html、word、pdf文件中,content内的内容可能非常复杂,样式非常多,还有可能标签不标准,不对称,并且有中文,如果拿到服务端去处理,比较复杂,下面分别完善三个导出方法。
导出文件时需要选择导出目录,那么如何弹出窗口选择目录呢?
function getExportPath() {
var shell = new ActiveXObject("Shell.Application");
var folder = shell.BrowseForFolder(0, '请选择存储目录', 0x);
if(folder != null) {
filePath = folder.Items().Item().P
return fileP
要使上段代码生效,需要对IE浏览器设置一下,如下图:
设置完之后,直接在浏览器运行还可能出现没有权限的问题,那就需要将html部署在服务器上,让后将当前服务器的访问地址设置为可信站点。
导出HTML:
function exportHtml {
var filePath = getExportPath();
if(filePath != null) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
file = fso.createtextfile(filePath + "/测试导出.html",true);// 创建文件
file.WriteLine(content.innerHTML);// 写入数据
alert("导出成功");
} catch (e) {
alert("导出失败");
} finally {
if(file != null)
file.close();// 关闭连接
导出WORD:
function exportWord() {
var filePath = getExportPath();
if(filePath != null) {
var word = new ActiveXObject("Word.Application");
var doc = word.Documents.Add("", 0, 1);
var range = doc.Range(0, 1);
var sel = document.body.createTextRange();
sel.moveToElementText(content);
} catch (notE) {
alert("导出数据失败,没有数据可以导出。");
window.close();
sel.select();
sel.execCommand("Copy");
range.Paste();
//word.Application.Visible =// 控制word窗口是否显示
doc.saveAs(filePath + "/导出测试.doc");// 保存
alert("导出成功");
} catch (e) {
alert("导出数据失败,需要在客户机器安装Microsoft Office Word(不限版本),将当前站点加入信任站点,允许在IE中运行ActiveX控件。");
} finally {
try {word.quit();// 关闭word窗口} catch (ex) {}
var filePath = getExportPath();
if(filePath != null) {
var word = new ActiveXObject("Word.Application");
var doc = word.Documents.Add("", 0, 1);
var range = doc.Range(0, 1);
var sel = document.body.createTextRange();
sel.moveToElementText(content);
} catch (notE) {
alert("导出数据失败,没有数据可以导出。");
window.close();
sel.select();
sel.execCommand("Copy");
range.Paste();
//word.Application.Visible =// 控制word窗口是否显示
doc.saveAs(filePath + "/导出测试.pdf", 17);// 保存为pdf格式
alert("导出成功");
} catch (e) {
alert("导出数据失败,需要在客户机器安装Microsoft Office Word 2007以上版本,将当前站点加入信任站点,允许在IE中运行ActiveX控件。");
} finally {
try {word.quit();// 关闭word窗口} catch (ex) {}
导出PDF废了一番周折,saveAs方法有一串参数,这里我只用到了前两个,第一个参数是保存文件名称,第二个参数是保存文件格式,office 支持将当前word另存为PDF格式,第二个参数是VB或C#环境下枚举类WdSaveFormat的一个值,经过多次弯曲的查询,终于查到其各个变量对应值。
Description
wdFormatDocument
Microsoft Office Word 97 - 2003 binary file format.
wdFormatDOSText
Microsoft DOS text format.
wdFormatDOSTextLineBreaks
Microsoft DOS text with line breaks preserved.
wdFormatEncodedText
Encoded text format.
wdFormatFilteredHTML
Filtered HTML format.
wdFormatFlatXML
Open XML file format saved as a single XML file.
wdFormatFlatXML
Open XML file format with macros enabled saved as a single XML file.
wdFormatFlatXMLTemplate
Open XML template format saved as a XML single file.
wdFormatFlatXMLTemplateMacroEnabled
Open XML template format with macros enabled saved as a single XML file.
wdFormatOpenDocumentText
OpenDocument Text format.
wdFormatHTML
Standard HTML format.
wdFormatRTF
Rich text format (RTF).
wdFormatStrictOpenXMLDocument
Strict Open XML document format.
wdFormatTemplate
Word template format.
wdFormatText
Microsoft Windows text format.
wdFormatTextLineBreaks
Windows text format with line breaks preserved.
wdFormatUnicodeText
Unicode text format.
wdFormatWebArchive
Web archive format.
wdFormatXML
Extensible Markup Language (XML) format.
wdFormatDocument97
Microsoft Word 97 document format.
wdFormatDocumentDefault
Word default document file format. For Word 2010, this is the DOCX format.
wdFormatPDF
PDF format.
wdFormatTemplate97
Word 97 template format.
wdFormatXMLDocument
XML document format.
wdFormatXMLDocumentMacroEnabled
XML document format with macros enabled.
wdFormatXMLTemplate
XML template format.
wdFormatXMLTemplateMacroEnabled
XML template format with macros enabled.
wdFormatXPS
XPS format.
使用客户端的导出方式优缺点都是显而易见的。
优点:原样导出,代码简单,不用为样式复杂的HTML导出发愁;
缺点:依赖客户端,只能在IE下使用,浏览器安全降低。
好了,先写这么多,大家晚安。
【上篇】【下篇】R语言结果输出至word的方法_百度文库
您的浏览器Javascript被禁用,需开启后体验完整功能,
享专业文档下载特权
&赠共享文档下载特权
&10W篇文档免费专享
&每天抽奖多种福利
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
R语言结果输出至word的方法
&&本文介绍了利用com接口将R和word互连的方法,并利用r2wd程序包撰写一个简单的自动报告。
阅读已结束,下载本文需要
想免费下载本文?
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
加入VIP
还剩1页未读,
定制HR最喜欢的简历
你可能喜欢Qt之导出PDF、HTML和Word(二)
五、HTML与Word
搜索"Qt操作Word",可以找到通过QAxObject和COM
Object联合直接读写Word的方法。但是,这个方法用起来不是很方便,在次,我介绍一种另类的方法,就是将“html格式代码保存到QString”,然后将QString导出为“.doc文件”。类似于直接保存“.html文件”,不同的是文件后缀名。如下示例代码:
void SaveReportThread::SaveToWord()
QString ReportPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); // 必须把路径中的'/'转换成'\\'
if (m_bSaveAll)
ReportPath += "\\TestReport_All.pdf";
ReportPath += "\\TestReport_" + m_pMainwindow-&m_strCurrentItemName + ".pdf";
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(ReportPath);
QString strH
//基本信息
ReportPath = QDir::toNativeSeparators(QCoreApplication::applicationDirPath()); // 必须把路径中的'/'转换成'\\'
if (m_bSaveAll)
ReportPath += "\\TestReport_All.doc";
ReportPath += "\\TestReport_" + m_pMainwindow-&m_strCurrentItemName + ".doc";
QFile WordDoc(ReportPath);
WordDoc.open(QIODevice::WriteOnly | QIODevice::Truncate );
QTextStream stream(&WordDoc);
stream && strHtml &&
使用Qt的QAxObject将Excel文件转成CSV文本文件
Qt之导出PDF、HTML和Word(一)
Qt 生成word、pdf文档
使用Qt生成PDF文件
通过QT 转换html文件为word文档
Qt开发:生成pdf文件
Qt利用QGraphicsScene编写Word排版工具导出PDF
Qt之导出PDF、HTML和Word(三)
没有更多推荐了,}

我要回帖

更多关于 pdf转word格式保持不变 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信