PHP生成便于打印的网页

很多新闻和信息站点都提供了一种生成便于打印的网页的方法,所产生的页面的排版布局更有利于打印机的打印输出,这种方法方便了我们从网页上直接打印我们所需的内容,而不必为格式不规整伤脑筋,或者粘贴到文本编辑器中重新排版。然而,我却没看到有多少网站详细解释这些是如何实现的,在这里我提供一小段代码——用PHP来实现生成便于打印的网页并不是像想象的那么难,希望对大家有帮助。

要生成便于打印的网页,需要我们做哪些工作呢?这主要取决于你的网站特点,和你想要生成的版式特征,不过有一些基本处理需要完成:

1、 页宽——生成页面的宽度必须限制,要打印A4的纸,大约网页要在630像素宽。
2、 页面背景色——为了美观,很多网页使用了不同的背景色和背景图片,但是作为要打印的网页,最合适效果的还是白底黑字为好。
3、 广告条——移除页面上的广告
4、 表格的背景色——我们经常在表格中用颜色来强调信息和标题,这些也必须移除。
5、 链接——页面中的超链接也必须改变以使URL可见,例如:

1<a href="http://www.gbdirect.co.uk/">GBDirect</a>

应显示为GBDirect (http://www.gbdirect.co.uk/)
6、 菜单——菜单是最难被禁止的,然而如果你的页面是使用模板来构建的话,那么最简单的方法是换用便于打印的没有菜单的模板。

这些生成便于打印页面的所有方法,都是非常简单的,需要实现的时候你可以被下面的代码放到网页中:

1<a href="pfp.php?page=&lt;?=$page?&gt;">;   
2<img alt="Click here to produce a printer friendly page" border="0" height="36" src="printer.gif" width="36"/>
3<font face="arial, helvetica" size="2">   
4Printer Friendly Version   
5</font>
6</a>

把当前页面的名称传递到pfp.php程序中,这个程序使用PHP的“file”函数把页面作为一个字符串来处理。当这个页面被载入的时候,程序就可以增加、改写或删除HTML片段。

 1<html>
 2<head>
 3<base href="http://&lt;? echo $HTTP_HOST ?&gt;/"/>
 4<meta content="no index, no follow" name="robots"/>
 5<title>Printer Friendly Page</title>
 6</head>
 7<body bgcolor="white">
 8<font face="Arial,Helvetica">
 9<table border="0" cellpadding="5" cellspacing="0" width="630">
10<tr>
11<td valign="top">
12<?   
13// check if the filename for the page exists   
14if (!file_exists("$page.inc"))   
15{   
16echo "<strong>Error - The page <?=$page?>".   
17"does not exist on this site.";   
18}   
19else   
20{   
21// 得到页面的内容并把它放到一个字符串中   
22$fcontents = join('', file("$page.inc"));   
23  
24// 忽略颜色属性,转换以’ignore’替代’color’   
25  
26$fcontents = ereg_replace('color','ignore',$fcontents);   
27  
28// 去除超链接中的 “_blank”   
29$fcontents = ereg_replace('target=\"_blank\"','',$fcontents);   
30  
31// 替换标记   
32$fcontents = ereg_replace('','',$fcontents);   
33  
34// 显示URL的绝对地址   
35$fcontents = ereg_replace('<a[^h]*href="(http: [^"]*)"[^="">]*&gt;;([^]*)',   
36'<strong>\\\2</strong><em>(\\\1)</em>',$fcontents);   
37  
38// 把相对链接转为绝对链接   
39$fcontents = ereg_replace(   
40'<a[^h]*href="([^"]*)"[^>]*&gt;([^]*)',   
41"<strong>\\\2</strong><em>(http://$HTTP_HOST/\\\1)</em>";,   
42$fcontents);   
43  
44// 背景颜色改回白色   
45$fcontents = ereg_replace('<body $fcontents="ereg_replace('','&lt;/a" $fcontents);="" any="" bgcolor',="" bgignore','<body="" element="" end="" if="" left="" link="" markers="" restore="">',$fcontents);   
46  
47// 输出页面   
48echo $fcontents;   
49}   
50?&gt;   
51</body></a[^h]*href="([^"]*)"[^></a[^h]*href="(http:></td>
52</tr>
53<tr>
54<td align="center"><hr width="90%"/></td>
55</tr>
56<tr>
57<td align="center">
58<? include("$page_path/footer.inc"); ?>
59</td>
60</tr>
61</table>
62</font>
63</body>
64</html>

这样便于打印的页面就生成了,希望对大家能有帮助。

(译自PHPBulider/Mark Spink)

Published At
Categories with Web编程
Tagged with
comments powered by Disqus