Visual Basic.NET 7.x (2002/03)Visual Basic 9 (2008)Visual Basic 8 (2005)Windows Vista.NET 1.0Windows 2003.NET 1.1.NET 3.0Windows 2000高级Windows XP.NET 2.0.NET 3.5中级Windows.NETVisual Basic
通用打印, 无需 Office
使用免费的 Word Viewer 2003/2007 和一些 XML 文档,您可以随时随地打印任何内容。
引言
这是一种可靠、易于维护、无需额外库的打印解决方案。只需下载免费的 Microsoft Word Viewer。创建一些 XML 模板,让代码为您完成工作。
背景
我找了很长时间才找到一个好的打印解决方案,它可以填充模板,并且不需要驱动程序或引用。
首先,我们需要一个 Word 2003(或 2007)XML 文件,用作模板源。由于此文件不像 docx 或开源替代方案 odt 那样被压缩,我们可以将其作为文本文件读取并替换,而不会出现任何问题。在 XML 模板中,我们放置用于替换的“TEXTFIELDS”。在本例中,我使用标记 #...# 作为替换字段。
首先,我们读取源文件,进行替换,然后写入临时打印文件。因此,我们始终保留原始模板。
Dim BRONDOCUMENT As String = "test.xml" ' Path to then source file
TEMPDOCUMENT = "TEMP.xml" 'this will be the output file with the changes
Dim fileContents As String
fileContents = My.Computer.FileSystem.ReadAllText(BRONDOCUMENT)
' WORD xml is not zipped so whe can copy an replace everthing without any problem
' I used a external textfile with the data to change. In this example whe do it inhere.
fileContents = fileContents.Replace("#NAAM#", "DE CAT BEN")
fileContents = fileContents.Replace("#ADRESSE#", "A STREET IN BELGIUM")
fileContents = fileContents.Replace("#URL#", "%22http://www.hetnetop.be/%22">WWW.HETNETOP.BE")
fileContents = fileContents.Replace("#CITY#", "KORTRIJK")
'etc....
My.Computer.FileSystem.WriteAllText(TEMPDOCUMENT, fileContents, False)
然后,我们所要做的就是创建一些按钮:打印、查看/编辑和取消。
'PRINT
'be sure that xml is assosiated with MS word or wordview
Process.Start(TEMPDOCUMENT) 'you can at some minimized window things here
'STARTS PRINTING THE WORD VIEW WITH SENDKEYS
My.Computer.Keyboard.SendKeys("^p", True)
My.Computer.Keyboard.SendKeys("~", True)
'CLOSE THE WORDVIEUW PROGRAM
For Each proc As Process In Process.GetProcesses()
If InStr(proc.MainWindowTitle, "TEMP") > 0 Then proc.CloseMainWindow()
Next
“查看/编辑”按钮只是调用“PROCESS.START(TEMPDOCUMENT)”,这样我们就可以以其全部荣耀获得 Word Viewer。
而且,猜猜看,“取消”只是结束程序……非常简单!但在实践中非常快速和可靠!
有了这个概念,您可以创建一个通用的 Windows 打印引擎,输入源模板 XML 文件和填充数据的 XML 文件,这样就可以从其他程序调用它,而无需解决打印可能带来的所有问题……
PS:测试文件 TEST.XML 位于 bind\debug 目录中。