600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 打印网页中特定内容

打印网页中特定内容

时间:2021-08-09 21:37:25

相关推荐

打印网页中特定内容

由于工作的需要,要求打印网页。而且是网页中的指定内容。有点多次一举“可是这就是客户的需求!!~”(某高人语)。收集了两个比较合适的解决方法。

首先是用JAVASCRIPT,以下是函数

<scriptlanguage="javascript"type="text/javascript">

<!--

functionButton3_onclick() {

bdhtml=window.document.body.innerHTML;

sprnstr="<!--startprint-->";

eprnstr="<!--endprint-->";

prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);

prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));

window.document.body.innerHTML=prnhtml;

window.print();

}

</script>

应用时把要打印的内容放到<!--startprint-->和<!--endprint-->之间。

二是C# documment类和print类的实现:

using System;

using ponentModel;

using System.Collections;

using System.Drawing;

using System.Drawing.Printing;

using System.Globalization;

using System.IO;

usingPrint= System.Drawing.Printing.PrintDocument;

namespace Sanxing.NdtReprot.Internal

{

/**////<summary>

///表示专用于大量文本打印的对象,该对象将输出至打印机。

///</summary>

[Description("表示专用于大量文本打印的对象,该对象将输出至打印机。")]

internalsealedclassTextPrintDocument:Print,IDisposable

{

私有变量#region私有变量

privateFont_printfont;

privateFont_headerFooterFont;

privatePen_penHeaderFooterLine;

privatePrintTextMode_printMode;

privatebool_printLineNumbers;

privatebool_printHeader;

privatebool_printFooter;

privatestring_header;

privatestring_footer;

privateTextReader_sr;

privateArrayList_buffer;

privatebool_emptyBuffer;

privateint_totalPageLines;

privateint_currentPageLine;

privatestring_stringToPrint;

privateint_currentPageNumber;

privateint_currentLine;

privateint_totalPrintedPages;

privateconststringDEFAULT_HEADER="&n";

privateconststringDEFAULT_FOOTER="&r&p";

privatestring[]_dateFormat={

"dddd","ddd","dd","d","D","MMMM","MMM","MM","m","yyyy","yy","y","f",

"F","g","G","r","s","t","T","u","U",

};

#endregion

属性#region属性

/**////<summary>

///设置要从中独取打印文本的<seecref="Stream"/>对象。

///</summary>

[Category("内容"),Description("设置要从中独取打印文本的数据流。")]

internalStreamContentStream

{

set

{

if(value!=null)

_sr=newStreamReader(value);

}

}

/**////<summary>

///获取或设置打印内容文本的字体。

///</summary>

[Category("内容"),Description("获取或设置打印内容文本的字体。")]

internalFontBodyFont

{

get{return_printfont;}

set{_printfont=value;}

}

/**////<summary>

///获取或设置打印页眉页脚文本的字体。

///</summary>

[Category("内容"),Description("获取或设置打印页眉页脚文本的字体。")]

internalFontHeaderFooterFont

{

get{return_headerFooterFont;}

set{_headerFooterFont=value;}

}

/**////<summary>

///获取或设置打印模式。

///</summary>

[Category("内容"),Description("获取或设置打印模式。"),DefaultValue(PrintTextMode.WrapText)]

internalPrintTextModePrintMode

{

get{return_printMode;}

set{_printMode=value;}

}

/**////<summary>

///获取或设置每页打印的行数。

///</summary>

[Category("内容"),Description("获取或设置每页打印的行数。")]

internalboolPrintLineNumber

{

get{return_printLineNumbers;}

set{_printLineNumbers=value;}

}

/**////<summary>

///获取或设置一个值,该值指示是否打印页眉部分。

///</summary>

[Category("内容"),Description("获取或设置一个值,该值指示是否打印页眉部分。"),DefaultValue(false)]

internalboolPrintHeader

{

get{return_printHeader;}

set{_printHeader=value;}

}

/**////<summary>

///获取或设置一个值,该值指示是否打印页脚部分。

///</summary>

[Category("内容"),Description("获取或设置一个值,该值指示是否打印页脚部分。"),DefaultValue(false)]

internalboolPrintFooter

{

get{return_printFooter;}

set{_printFooter=value;}

}

/**////<summary>

///获取或设置要进行打印的文本。

///</summary>

[Category("内容"),Description("获取或设置要进行打印的文本。")]

internalstringText

{

get{return_stringToPrint;}

set{_stringToPrint=value;}

}

/**////<summary>

///获取或设置要打印在页眉部分的文本。

///</summary>

[Description("获取或设置要打印在页眉部分的文本。"),DefaultValue(""),Category("内容")]

internalstringHeader

{

get{return_header;}

set{_header=value;}

}

/**////<summary>

///获取或设置要打印在页脚部分的文本。

///</summary>

[Category("内容"),Description("获取或设置要打印在页脚部分的文本。"),DefaultValue("")]

internalstringFooter

{

get{return_footer;}

set{_footer=value;}

}

#endregion

构造器#region构造器

/**////<summary>

///使用默认值初始化<b>TextPrintDocument</b>类的新实例。

///</summary>

publicTextPrintDocument():base()

{

_sr=null;

_stringToPrint=string.Empty;

_penHeaderFooterLine=Pens.Black;

_header=DEFAULT_HEADER;

_footer=DEFAULT_FOOTER;

}

/**////<summary>

///使用内容流以及字体初始化<b>TextPrintDocument</b>类的新实例。

///</summary>

///<paramname="Stream"></param>

///<paramname="BodyFont"></param>

publicTextPrintDocument(StreamStream,FontBodyFont):base()

{

if(Stream==null)

thrownewArgumentNullException("Stream");

_sr=newStreamReader(Stream);

if(BodyFont==null)

_printfont=newFont("宋体",3.5f,FontStyle.Regular,GraphicsUnit.Millimeter);

else

_printfont=BodyFont;

_stringToPrint=string.Empty;

_penHeaderFooterLine=Pens.Black;

_header=DEFAULT_HEADER;

_footer=DEFAULT_FOOTER;

}

/**////<summary>

///

///</summary>

///<paramname="PrintText"></param>

///<paramname="BodyFont"></param>

publicTextPrintDocument(stringPrintText,FontBodyFont)

:base()

{

if(PrintText==null||PrintText==string.Empty)

thrownewArgumentNullException("PrintText");

_stringToPrint=PrintText;

_sr=null;

if(BodyFont==null)

_printfont=newFont("宋体",3.5f,FontStyle.Regular,GraphicsUnit.Millimeter);

else

_printfont=BodyFont;

_penHeaderFooterLine=Pens.Black;

_header=DEFAULT_HEADER;

_footer=DEFAULT_FOOTER;

}

#endregion

方法#region方法

/**////<summary>

///在处理打印内容前,执行必要操作。

///</summary>

///<paramname="e"></param>

protectedoverridevoidOnBeginPrint(PrintEventArgse)

{

base.OnBeginPrint(e);

if(_sr==null&&_stringToPrint==string.Empty)

thrownewInvalidOperationException("没有发现要进行打印处理的文档或数据流。");

//检查是否有文本,有就生成读取器。

if(_stringToPrint!=string.Empty)

_sr=newStringReader(_stringToPrint);

//检查页眉页脚的字体

if(_headerFooterFont==null)

_headerFooterFont=_printfont;

_currentPageNumber=0;

_totalPrintedPages=0;

_currentLine=1;

}

/**////<summary>

///打印完毕后,执行必要操作。

///</summary>

///<paramname="e"></param>

protectedoverridevoidOnEndPrint(PrintEventArgse)

{

base.OnEndPrint(e);

if(_sr!=null)

_sr.Close();

_totalPrintedPages=_currentPageNumber;

}

/**////<summary>

///在打印前,生成打印内容。

///</summary>

///<paramname="e"></param>

protectedoverridevoidOnPrintPage(PrintPageEventArgse)

{

base.OnPrintPage(e);

Graphicsgfx=e.Graphics;

PageSettingspageset=DefaultPageSettings;//页面设置

floatprintAreaHeight=pageset.PaperSize.Height-(pageset.Margins.Top+pageset.Margins.Bottom);

floatprintAreaWidth=pageset.PaperSize.Width-(pageset.Margins.Left+pageset.Margins.Right);

floatmarginLeft=pageset.Margins.Left;

floatmarginTop=pageset.Margins.Top;

if(DefaultPageSettings.Landscape)

{

floattmp=printAreaHeight;

printAreaHeight=printAreaWidth;

printAreaWidth=tmp;

}

if(_buffer==null)

_buffer=newArrayList(_totalPageLines);

floatcharHeight=_printfont.GetHeight(gfx);

floatheaderFooterCharHeight=_headerFooterFont.GetHeight(gfx);

floatheaderFooterHeight=headerFooterCharHeight+charHeight;

RectangleFrectHeader=

newRectangleF(marginLeft,marginTop,printAreaWidth,_printHeader?headerFooterHeight:0);

RectangleFrectFooter=

newRectangleF(marginLeft,marginTop+printAreaHeight,printAreaWidth,

_printFooter?headerFooterHeight:0);

if(_printHeader)//检查是否要输出页头

DrawHeader(gfx,rectHeader);

_totalPageLines=Convert.ToInt32((printAreaHeight-rectFooter.Height-rectHeader.Height)/charHeight);

_currentPageLine=0;

if(_stringToPrint==null)

_stringToPrint=GetNextLine();

while((_currentPageLine<=_totalPageLines)&&(_stringToPrint!=null))

{

floatyPos=rectHeader.Bottom+(_currentPageLine*charHeight);

//Calculateprintingrectanglearea

RectangleFrectTextLine=newRectangleF(marginLeft,yPos,printAreaWidth,charHeight);

_stringToPrint=DrawTextLine(gfx,_stringToPrint,rectTextLine);

PutNextLine(_stringToPrint);

_currentPageLine++;

_currentLine++;

_stringToPrint=GetNextLine();

}

if(_printFooter)

DrawFooter(gfx,rectFooter);

_currentPageNumber++;

e.HasMorePages=HasMorePages();

}

#endregion

私有帮助器#region私有帮助器

/**////<summary>

///获取下一行的文本内容。

///</summary>

///<returns></returns>

privatestringGetNextLine()

{

stringline=null;

if(_printMode==PrintTextMode.WrapText)

{

if(_buffer.Count==0)

line=_sr.ReadLine();

else

{

line=(string)_buffer[0];

_buffer.RemoveAt(0);

}

}

else

{

if(_emptyBuffer)

{

if(_currentPageLine<_buffer.Count)

{

line=(string)_buffer[_currentPageLine];

_buffer[_currentPageLine]=null;

}

else

{

if(!HasBufferChars())

{

_buffer.Clear();

_emptyBuffer=false;

}

}

}

else

{

if(_currentPageLine<=_totalPageLines)

line=_sr.ReadLine();

_emptyBuffer=HasBufferChars();

if(line==null)

_emptyBuffer=HasBufferChars();

}

}

returnline;

}

/**////<summary>

///将处理过程推进到下一行。

///</summary>

///<paramname="line"></param>

privatevoidPutNextLine(stringline)

{

if(_printMode==PrintTextMode.WrapText)

{

if(line.Length>0)

{

if(_buffer.Count==0)

_buffer.Add(line);

else

_buffer[0]=line;

}

}

elseif(_printMode==PrintTextMode.BannerLike)

{

if(_currentPageLine<_buffer.Count)

_buffer[_currentPageLine]=line;

else

_buffer.Add(line);

}

}

privateboolHasMorePages()

{

intmoreChars=-1;

try

{

moreChars=_sr.Peek();

}

catch(Exception)

{}

return(moreChars!=-1)||_emptyBuffer;

}

privateboolHasBufferChars()

{

foreach(stringstrin_buffer)

{

if(str.Length>0)

returntrue;

}

returnfalse;

}

privatestringDrawTextLine(Graphicsgfx,stringtext,RectangleFrectangle)

{

StringFormatfmt=newStringFormat();

if(_printLineNumbers)

{

FontfnLine=newFont(FontFamily.GenericMonospace,_printfont.Size);

stringlineStr=String.Format("{0,4:G}",_currentLine);

SizeFszfLine=gfx.MeasureString(lineStr,fnLine,rectangle.Size,fmt);

gfx.DrawString(lineStr,fnLine,Brushes.Black,rectangle,fmt);

rectangle.Inflate(-(szfLine.Width+_printfont.Size),0);

}

intcharactersOnLine=GetLineBreakCharPosition(gfx,text,rectangle);

gfx.DrawString(text,_printfont,Brushes.Black,rectangle,fmt);

returntext.Substring(charactersOnLine);

}

privateintGetLineBreakCharPosition(Graphicsgfx,stringtext,RectangleFrectangle)

{

StringFormatfmt=newStringFormat(StringFormatFlags.MeasureTrailingSpaces);

intcharactersOnLine=0;

intlines=0;

SizeFsizeText=gfx.MeasureString(text,_printfont,rectangle.Size,fmt,outcharactersOnLine,outlines);

stringrem=text.Substring(0,charactersOnLine);

if(rem.EndsWith("")&&(charactersOnLine<text.Length))

{

stringnoSpaces=rem.TrimEnd(newChar[]{''});

intnSpaces=rem.Length-noSpaces.Length;

SizeFsizeChunk=

gfx.MeasureString(noSpaces,_printfont,rectangle.Size,fmt,outcharactersOnLine,outlines);

stringspacer=String.Empty;

while(sizeChunk.Width<=rectangle.Width)

{

spacer+="";

sizeChunk=gfx.MeasureString(noSpaces+spacer,_printfont,newPointF(0,0),fmt);

}

charactersOnLine+=spacer.Length-((sizeChunk.Width>rectangle.Width)?1:0);

}

returncharactersOnLine;

}

/**////<summary>

///打印页眉。

///</summary>

///<paramname="gfx"></param>

///<paramname="rectangle"></param>

privatevoidDrawHeader(Graphicsgfx,RectangleFrectangle)

{

StringFormatfmtHeader=newStringFormat();

stringheader=MakeHeaderFooterString(Header,reffmtHeader);

gfx.DrawString(header,_headerFooterFont,Brushes.Black,rectangle,fmtHeader);

floatyPos=rectangle.Top+(_headerFooterFont.GetHeight(gfx)+2);

if(yPos<=rectangle.Bottom)

gfx.DrawLine(_penHeaderFooterLine,rectangle.Left,yPos,rectangle.Right,yPos);

}

/**////<summary>

///打印页脚。

///</summary>

///<paramname="gfx"></param>

///<paramname="rectangle"></param>

privatevoidDrawFooter(Graphicsgfx,RectangleFrectangle)

{

StringFormatfmtHeader=newStringFormat();

stringheader=MakeHeaderFooterString(Footer,reffmtHeader);

fmtHeader.LineAlignment|=StringAlignment.Far;

gfx.DrawString(header,_headerFooterFont,Brushes.Black,rectangle,fmtHeader);

floatyPos=rectangle.Bottom-(_headerFooterFont.GetHeight(gfx)+2);

if(yPos>=rectangle.Top)

gfx.DrawLine(_penHeaderFooterLine,rectangle.Left,yPos,rectangle.Right,yPos);

}

privatestringMakeHeaderFooterString(stringtemplate,refStringFormatformat)

{

stringheaderFooter=template;

intix=headerFooter.IndexOf("&l");

if(ix!=-1)

{

format.Alignment=StringAlignment.Near;

headerFooter=headerFooter.Remove(ix,2);

}

ix=headerFooter.IndexOf("&r");

if(ix!=-1)

{

format.Alignment=StringAlignment.Far;

headerFooter=headerFooter.Remove(ix,2);

}

ix=headerFooter.IndexOf("&c");

if(ix!=-1)

{

format.Alignment=StringAlignment.Center;

headerFooter=headerFooter.Remove(ix,2);

}

headerFooter=headerFooter.Replace("&p",(_currentPageNumber+1).ToString());

headerFooter=headerFooter.Replace("&n",DocumentName);

DateTimedt=DateTime.Now;

ix=0;

while((ix=headerFooter.IndexOf("%"))!=-1)

{

boolfound=false;

for(inti=0;i<_dateFormat.Length;i++)

{

stringfmt="%"+_dateFormat[i];

if(headerFooter.Substring(ix,fmt.Length)==fmt)

{

stringdate=dt.ToString(_dateFormat[i],DateTimeFormatInfo.InvariantInfo);

headerFooter=headerFooter.Remove(ix,fmt.Length);

headerFooter=headerFooter.Insert(ix,date);

found=true;

break;

}

}

if(!found)

headerFooter=headerFooter.Remove(ix,1);

}

returnheaderFooter;

}

#endregion

IDisposable成员#regionIDisposable成员

/**////<summary>

///移除由<b>TextPrintDocument</b>使用的所有托管资源。

///</summary>

publicnewvoidDispose()

{

Dispose(true);

}

/**////<summary>

///

///</summary>

///<paramname="disposing"></param>

protectedoverridevoidDispose(booldisposing)

{

if(disposing)

{

lock(this)

{

if(_sr!=null)

_sr.Dispose();

}

GC.SuppressFinalize(true);

}

base.Dispose(disposing);

}

/**////<summary>

///供<seecref="GC"/>使用的清理托管资源的方法。

///</summary>

~TextPrintDocument()

{

Dispose(false);

}

#endregion

}

/**////<summary>

///指定打印文本的模式。

///</summary>

internalenumPrintTextMode

{

/**////<summary>

///换行文本。

///</summary>

WrapText,

Truncate,

BannerLike

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。