代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
调用虚拟打印机,文件转pdf
作者:
Dezai.CN
/ 发布于
2013/2/20
/
814
using System; using System.Data; 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 System.IO; using Microsoft.Win32; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; using System.Reflection; using System.Drawing.Imaging; using iTextSharp; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html; using iTextSharp.text.html.simpleparser; using iTextSharp.text.xml; using ACAWebThumbLib; using System.Drawing.Printing; /// <summary> /// printerPdf 的摘要说明 /// </summary> public class printerPdf { public printerPdf() { // // TODO: 在此处添加构造函数逻辑 // } private string fileSavePath = System.Web.HttpContext.Current.Server.MapPath("~/upload"); [DllImport("winspool.drv")] public static extern bool SetDefaultPrinter(string Name); [DllImport("user32.dll")] public static extern bool SendNotifyMessage(int HWND_BROADCAST, int WM_WININICHANGE, int f_int, string f_Note); [DllImport("shell32.dll ")] public static extern IntPtr ShellExecute( IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd); [DllImport("User32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr FindWindowEx(IntPtr parent /*HWND*/, IntPtr next /*HWND*/, string sClassName, IntPtr sWindowTitle); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetWindowText(IntPtr hWnd, out STRINGBUFFER ClassName, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); [DllImport("user32")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public struct STRINGBUFFER { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string szText; } System.Web.UI.Page workingPage = null; private string currentPrinterName = string.Empty; private string PrinterName = string.Empty; private string fileName = string.Empty; private string fileExtend = string.Empty; private string filePath = string.Empty; Object obj_printer_settings; const int HWND_BROADCAST = 0xFFFF; const int WM_WININICHANGE = 0x001A; Type oType = null; // public List<string> listExtend = new List<string>() { "jpg","jpeg","bmp","gif","png","doc","docx","txt","xls","xlsx","htm","html","xhtml" }; public printerPdf(System.Web.UI.Page _workingPage) { workingPage = _workingPage; } /// <summary> /// 读取文件的扩展名 /// </summary> /// <param name="strFileFullName"></param> /// <returns></returns> public string GetFileExtendName(string strFileFullName) { return strFileFullName.Substring(strFileFullName.LastIndexOf(".") + 1).ToLower(); } /// <summary> /// 读取文件名 /// </summary> /// <param name="strFileFullName"></param> /// <returns></returns> public string GetFileName(string strFileFullName) { string tmpFileName = strFileFullName.Substring(0,strFileFullName.LastIndexOf(".")); return tmpFileName.Substring(tmpFileName.LastIndexOf("\\")+1); } /// <summary> /// 获取printer信息 /// </summary> /// <param name="printerName"></param> /// <param name="obj_printer_settings"></param> public void GetPrinterName(ref string printerName, ref object printerSettings,ref System.Type oType) { string progid = "Bullzip.PDFPrinterSettings"; oType = System.Type.GetTypeFromProgID(progid); printerSettings = System.Activator.CreateInstance(oType); printerName = (string)oType.InvokeMember("GetPrinterName", System.Reflection.BindingFlags.InvokeMethod, null, printerSettings, null); } /// <summary> /// 获取ImageFormat /// </summary> /// <param name="extend"></param> /// <returns></returns> public System.Drawing.Imaging.ImageFormat GetImageFormat(string extend) { System.Drawing.Imaging.ImageFormat fomat = null; switch (extend.ToLower()) { case "jpg": case "jpeg": fomat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case "gif": fomat = System.Drawing.Imaging.ImageFormat.Gif; break; case "bmp": fomat = System.Drawing.Imaging.ImageFormat.Bmp; break; case "png": fomat = System.Drawing.Imaging.ImageFormat.Png; break; } return fomat; } //public void ConvertToPDF(string fileName) //{ // if (string.IsNullOrEmpty(fileName)) // return; // if (!listExtend.Contains(GetFileExtendName(fileName))) // return; // switch (GetFileExtendName(fileName)) // { // case"doc": // case "docx": // PrintDOCToPDF(fileName); // break; // case "xls": // case "xlsx": // PrintSheetToPDF (fileName); // break; // case "txt": // PrintNoteToPDF(fileName); // break; // case "htm": // case "html": // case "xhtml": // HtmlToPDF(fileName); // break; // default: // PrintImageToPDF(fileName); // break; // } //} /// <summary> /// Html转pdf /// </summary> /// <param name="fileName"></param> public void HtmlToPDF(string fileName) { string tmpName=GetFileName(fileName); filePath=fileSavePath + "\\"+tmpName+".jpg"; ThumbMakerClass markerClass = new ThumbMakerClass(); markerClass.SetURL(fileSavePath + "\\" + fileName); markerClass.StartSnap(); //markerClass.SetThumbSize(4000, markerClass.GetThumbHeight(), 0); markerClass.SaveImage(filePath); PrintImageToPDF(tmpName+".jpg"); if (File.Exists(filePath)) File.Delete(filePath); } /// <summary> /// image转pdf /// </summary> /// <param name="fileInputName"></param> public void PrintImageToPDF(string fileInputName) { Document document = null; PdfWriter writer=null; System.Drawing.Image sourceImg=null; iTextSharp.text.Image pdfImage=null; try { filePath = fileSavePath + "\\" + GetFileName(fileInputName) + ".pdf"; iTextSharp.text.Rectangle rectPageSize = new iTextSharp.text.Rectangle(PageSize.A4); rectPageSize = rectPageSize.Rotate(); document = new Document(rectPageSize, 25, 25, 25, 25); writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create)); document.Open(); sourceImg = System.Drawing.Image.FromFile(fileSavePath+"\\"+fileInputName); pdfImage = iTextSharp.text.Image.GetInstance(sourceImg,GetImageFormat(GetFileExtendName(fileInputName))); pdfImage.Alignment = iTextSharp.text.Image.ALIGN_CENTER; float height=document.Top - document.TopMargin; //图片原始大小 pdfImage.ScaleToFit(sourceImg.Width > document.Right?document.Right:sourceImg.Width,sourceImg.Height>height?height:sourceImg.Height); //pdfImage.ScaleToFit(document.Right ,height); document.Add(pdfImage); sourceImg = null; pdfImage = null; document.Close(); writer.Close(); } catch(Exception e) { sourceImg = null; pdfImage = null; document.Close(); writer.Close(); } } /// <summary> /// txt转换为pdf /// </summary> /// <param name="file_inputname"></param> public void PrintTXTToPDF(string fileInputName) { GetPrinterName(ref PrinterName, ref obj_printer_settings,ref oType); try { PrintDocument prtdoc = new PrintDocument(); currentPrinterName = prtdoc.PrinterSettings.PrinterName; //获取默认的打印机名 //更改默认打印机 SetDefaultPrinter(PrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); if (fileInputName == "") { return; } filePath = fileSavePath + "\\" + GetFileName(fileInputName) + ".pdf"; oType.InvokeMember("Init", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, null); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "output",filePath }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "showsettings", "never" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowPDF", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgress", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgressFinished", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "SuppressErrors", "yes" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ConfirmOverwrite", "no" }); oType.InvokeMember("WriteSettings", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { true }); if (File.Exists(filePath) == true) { File.Delete(filePath); } ShellExecute(IntPtr.Zero, "print", fileSavePath+"\\"+fileInputName, "", "", 0); IntPtr hParent = IntPtr.Zero; IntPtr hNext = IntPtr.Zero; string sClassNameFilter = "#32770"; for (int f_intStep = 1; f_intStep < 20000; f_intStep++) { hNext = FindWindowEx(hParent, hNext, sClassNameFilter, IntPtr.Zero); if (!hNext.Equals(IntPtr.Zero)) { ShowWindow(hNext, 0); } System.Threading.Thread.Sleep(100); if (File.Exists(filePath) == true) { break; } } obj_printer_settings = null; //更改默认打印机 SetDefaultPrinter(currentPrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); } catch (Exception e) { obj_printer_settings = null; //throw e; } } /// <summary> /// excel转换为pdf /// </summary> /// <param name="file_inputname"></param> public void PrintSheetToPDF(string fileInputName) { try { GetPrinterName(ref PrinterName, ref obj_printer_settings, ref oType); PrintDocument prtdoc = new PrintDocument(); currentPrinterName = prtdoc.PrinterSettings.PrinterName; //获取默认的打印机名 //更改默认打印机 SetDefaultPrinter(PrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); if (fileInputName == "") { return; } filePath = fileSavePath + "\\" + GetFileName(fileInputName) + ".pdf"; oType.InvokeMember("Init", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, null); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "output", filePath }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "showsettings", "never" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowPDF", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgress", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgressFinished", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "SuppressErrors", "yes" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ConfirmOverwrite", "no" }); oType.InvokeMember("WriteSettings", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { true }); if (File.Exists(filePath) == true) { File.Delete(filePath); } object objMissing = System.Type.Missing; object objValue = true; Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook objWorkbook = objExcel.Workbooks.Open(fileSavePath+"\\"+fileInputName, objMissing, objValue, objMissing, objMissing,objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing); objExcel.Visible = false; for (int i = 1; i < objWorkbook.Worksheets.Count; i++) { _Worksheet active_workbook = (_Worksheet)objExcel.Worksheets.get_Item(i); active_workbook.PageSetup.Zoom = false; active_workbook.PageSetup.FitToPagesWide = 1; active_workbook.PageSetup.FitToPagesTall = 10; } objExcel.ActiveWorkbook.PrintOut(objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing); for (int f_intStep = 1; f_intStep < 20000; f_intStep++) { System.Threading.Thread.Sleep(100); if (File.Exists(filePath) == true) { break; } } objWorkbook.Close(false, fileInputName, false); objExcel.Quit(); objWorkbook = null; objExcel = null; int k = 0; IntPtr t = new IntPtr(objExcel.Hwnd); GetWindowThreadProcessId(t, out k); System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); p.Kill(); obj_printer_settings = null; //更改默认打印机 SetDefaultPrinter(currentPrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); } catch (Exception e) { obj_printer_settings = null; //throw e; } } /// <summary> /// word 转换为pdf /// </summary> /// <param name="file_inputname"></param> public void PrintDOCToPDF(String fileInputName) { object appword; object doc; object docs; object docs1; try { GetPrinterName(ref PrinterName, ref obj_printer_settings, ref oType); PrintDocument prtdoc = new PrintDocument(); currentPrinterName = prtdoc.PrinterSettings.PrinterName; //获取默认的打印机名 //更改默认打印机 SetDefaultPrinter(PrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); if (fileInputName == "") { return; } filePath = fileSavePath + "\\" + GetFileName(fileInputName) + ".pdf"; oType.InvokeMember("Init", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, null); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "output", filePath }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "showsettings", "never" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowPDF", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgress", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ShowProgressFinished", "no" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "SuppressErrors", "yes" }); oType.InvokeMember("SetValue", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { "ConfirmOverwrite", "no" }); oType.InvokeMember("WriteSettings", System.Reflection.BindingFlags.InvokeMethod, null, obj_printer_settings, new object[] { true }); if (File.Exists(filePath) == true) { File.Delete(filePath); } System.Type wordType = System.Type.GetTypeFromProgID("Word.Application"); appword = System.Activator.CreateInstance(wordType); docs1 = wordType.InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty, null, appword, null); object all = appword.GetType().InvokeMember("AddIns", BindingFlags.GetProperty, System.Type.DefaultBinder, appword, null); docs1.GetType().InvokeMember("Unload", System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, all, new Object[] { false }); docs = wordType.InvokeMember("Documents", System.Reflection.BindingFlags.GetProperty, null, appword, null); wordType.InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, appword, new Object[] { false }); doc = docs.GetType().InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileSavePath+"\\"+fileInputName }); wordType.InvokeMember("PrintOut", System.Reflection.BindingFlags.InvokeMethod, null, appword, new Object[] { null }); IntPtr hParent = IntPtr.Zero; IntPtr hNext = IntPtr.Zero; string sClassNameFilter = "#32770"; for (int f_intStep = 1; f_intStep < 20000; f_intStep++) { hNext = FindWindowEx(hParent, hNext, sClassNameFilter, IntPtr.Zero); if (!hNext.Equals(IntPtr.Zero)) { ShowWindow(hNext, 0); } System.Threading.Thread.Sleep(100); if (File.Exists(filePath) == true) { break; } } object wdDoNotSaveChanges = 0; docs.GetType().InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { 0, 0, 0 }); wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, appword, new Object[] { 0, System.Reflection.Missing.Value, System.Reflection.Missing.Value }); docs = null; doc = null; docs1 = null; appword = null; obj_printer_settings = null; //更改默认打印机 SetDefaultPrinter(currentPrinterName.Trim()); //通知更改 SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, "windows"); } catch (Exception e) { docs = null; doc = null; appword = null; obj_printer_settings = null; //throw e; } } } ---------------------------------------------------- itextsharp.dll Interop.ACAWebThumbLib.dll Microsoft.Office.Interop.Excel.dll 引用以上dll文件 安装 gs811w32.exe Bullzip 虚拟打印 Adobe Acrobat 7.0 Professional
试试其它关键字
文件转pdf
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Dezai.CN
贡献的其它代码
(
4037
)
.
多线程Socket服务器模块
.
生成随机密码
.
清除浮动样式
.
弹出窗口居中
.
抓取url的函数
.
使用base HTTP验证
.
div模拟iframe嵌入效果
.
通过header转向的方法
.
Session操作类
.
执行sqlite输入插入操作后获得自动编号的ID
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3