一、PDF/WORD/EXCEL 转 XPS 转 第一页内容 转 图片

  • WORD、EXCEL转XPS (Office2010)
 public bool WordToXPS(string sourcePath, string targetPath)
{
bool result = false;
Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatXPS;
Microsoft.Office.Interop.Word.ApplicationClass application = null; Microsoft.Office.Interop.Word.Document document = null;
try
{
application = new Microsoft.Office.Interop.Word.ApplicationClass();
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.SaveAs2();
document.ExportAsFixedFormat(targetPath, exportFormat);
result = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
result = false;
}
finally
{
if (document != null)
{
document.Close();
document = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}
  • PDF转XPS (将机器上默认打印机设置为Microsoft XPS Document Writer)
        //Win32 Api定义
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfeter, string lpszClass, string lpszWindow); [DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, String lParam); [DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); //Win32消息定义
const uint WM_SETTEXT = 0x000c;
const uint WM_IME_KEYDOWN = 0x0290;
const uint WM_LBUTTONDOWN = 0x0201;
const uint WM_LBUTTONUP = 0x0202; private void button3_Click(object sender, EventArgs e)
{
string pdf_filepath = @"d:\原文件.pdf"; // 需要转换的PDF文件
string xps_filepath = @"d:\目标文件.xps"; // 目标XPS文件 System.Diagnostics.Process p = new System.Diagnostics.Process();
//不现实调用程序窗口,但是对于某些应用无效
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //采用操作系统自动识别的模式
p.StartInfo.UseShellExecute = true; //要打印的文件路径,可以是WORD,EXCEL,PDF,TXT等等
p.StartInfo.FileName = pdf_filepath;
//p.StartInfo.FileName = @"C:\Documents and Settings\Administrator\桌面\MouseWithoutBorders\2.bmp"; //指定执行的动作,是打印,即print,打开是 open
p.StartInfo.Verb = "print"; //开始
p.Start(); System.Threading.Thread.Sleep( * ); IntPtr hWnd = FindWindow("#32770", "文件另存为");
IntPtr hChild;
// 由于输入框被多个控件嵌套,因此需要一级一级的往控件内找到输入框
hChild = FindWindowEx(hWnd, IntPtr.Zero, "DUIViewWndClassName", String.Empty);
hChild = FindWindowEx(hChild, IntPtr.Zero, "DirectUIHWND", String.Empty);
hChild = FindWindowEx(hChild, IntPtr.Zero, "FloatNotifySink", String.Empty);
hChild = FindWindowEx(hChild, IntPtr.Zero, "ComboBox", String.Empty);
hChild = FindWindowEx(hChild, IntPtr.Zero, "Edit", String.Empty); // File name edit control
// 向输入框发送消息,填充目标xps文件名
SendMessage(hChild, WM_SETTEXT, IntPtr.Zero, xps_filepath);
// 等待1秒钟
System.Threading.Thread.Sleep();
// 找到对话框内的保存按钮
hChild = IntPtr.Zero;
hChild = FindWindowEx(hWnd, IntPtr.Zero, "Button", "保存(&S)");
// 向保存按钮发送2个消息,以模拟click消息,借此来按下保存按钮
PostMessage(hChild, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
PostMessage(hChild, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero); /***** 跟踪打印机队列中的文件打印状况,知道文件打印完成为止 *****/
// 调用本地打印机队列
System.Printing.LocalPrintServer prtSrv = new System.Printing.LocalPrintServer();
System.Printing.PrintQueue queue = prtSrv.GetPrintQueue("Microsoft XPS Document Writer"); //一直监视打印队列,知道打印队列中没有打印任务时结束
do
{
// 等待处理
System.Threading.Thread.Sleep();
// 读取队列的最新信息
queue.Refresh();
} while (queue.NumberOfJobs > ); MessageBox.Show("完成");
}
  • XPS转图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO; namespace Xps_Reader
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
BitmapEncoder bitmapEncoder = null;
MemoryStream memoryStream = new MemoryStream();
public Window1()
{
InitializeComponent(); AddCMD(ApplicationCommands.Open, MenuItem_Checked);
AddCMD(ApplicationCommands.Close, exitMenu_Checked);
AddCMD(ApplicationCommands.Save, saveMenu_Checked);
}
private XpsDocument xpsDocument; //绑定菜单命令
private void AddCMD(ICommand cmd,ExecutedRoutedEventHandler e) { var cb = new CommandBinding(cmd);
cb.Executed += new ExecutedRoutedEventHandler(e);
CommandBindings.Add(cb);
} public MemoryStream OutputStream
{
get;
private set;
}
//打开xps文件
private void MenuItem_Checked(object sender, ExecutedRoutedEventArgs e)
{ OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "xps|*.xps";
//dlg.Filter = "jpg|*.jpg";
if (dlg.ShowDialog() == true) {
try
{
if (xpsDocument != null) xpsDocument.Close(); xpsDocument = new XpsDocument(dlg.FileName, System.IO.FileAccess.Read);
FixedDocumentSequence documentPageSequence = xpsDocument.GetFixedDocumentSequence();
documentPageView1.Document = documentPageSequence;
bitmapEncoder = new JpegBitmapEncoder();
//for (int i = 0; i < documentPageSequence.DocumentPaginator.PageCount;i++ )
//{
// DocumentPage documentPage = documentPageSequence.DocumentPaginator.GetPage(i);
// RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)documentPage.Size.Width, (int)documentPage.Size.Height, 96.0, 96.0, PixelFormats.Pbgra32);
// targetBitmap.Render(documentPage.Visual);
// bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
//}
////bitmapEncoder.Save(memoryStream); DocumentPage documentPage = documentPageSequence.DocumentPaginator.GetPage();
RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)documentPage.Size.Width, (int)documentPage.Size.Height, 96.0, 96.0, PixelFormats.Pbgra32);
targetBitmap.Render(documentPage.Visual);
bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap)); xpsDocument.Close();
}
catch(Exception ex)
{
throw (ex);
} }
} private void exitMenu_Checked(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
private void saveMenu_Checked(object sender, ExecutedRoutedEventArgs e)
{
//创建一个保存对话框对象
SaveFileDialog sfd = new SaveFileDialog();
//XpsImage image = new XpsImage(); string a; //设置对话框的各项属性
sfd.Title = "转化为";
sfd.OverwritePrompt = true;
sfd.CheckPathExists = true;
sfd.Filter = "gif|*.gif"; if (sfd.ShowDialog() == true)
{
string strFileName = sfd.FileName;
bitmapEncoder.Save(memoryStream); Bitmap bitMap = new Bitmap(memoryStream);
bitMap.Save(strFileName); //this.OutputStream = memoryStream;
//bitmap.Save(strFileName, ImageFormat.Jpeg);
//this.Text = "Image Converter: " + strFileName; }
} private void MenuItem_Click(object sender, RoutedEventArgs e)
{ }
}
}

二、WORD/EXCEL 转PDF 转 第一页内容 转 图片

  • WORD/EXCEL 转 PDF (Office2010)
        /// <summary>
/// 把Word文件转换成为PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public bool WordToPDF(string sourcePath, string targetPath)
{
bool result = false;
Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatXPS;
Microsoft.Office.Interop.Word.ApplicationClass application = null; Microsoft.Office.Interop.Word.Document document = null;
try
{
application = new Microsoft.Office.Interop.Word.ApplicationClass();
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.SaveAs2();
document.ExportAsFixedFormat(targetPath, exportFormat);
result = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
result = false;
}
finally
{
if (document != null)
{
document.Close();
document = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}
  • PDF 转 图片 (Adobe Acrobat 9 Pro)
public static void ConvertPdf2Image(string pdfFilePath, string imageDirectoryPath,
int beginPageNum, int endPageNum, ImageFormat format, double zoom = )
{
Acrobat.CAcroPDDoc pdfDoc = null;
Acrobat.CAcroPDPage pdfPage = null;
Acrobat.CAcroRect pdfRect = null;
Acrobat.CAcroPoint pdfPoint = null; //生成操作Pdf文件的Com对象 pdfDoc = (Acrobat.CAcroPDDoc)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.PDDoc", ""); //检查输入参数
if (!pdfDoc.Open(pdfFilePath))
{
throw new FileNotFoundException(string.Format("源文件{0}不存在!", pdfFilePath));
} if (!Directory.Exists(imageDirectoryPath))
{
Directory.CreateDirectory(imageDirectoryPath);
} if (beginPageNum <= )
{
beginPageNum = ;
} if (endPageNum > pdfDoc.GetNumPages() || endPageNum <= )
{
endPageNum = pdfDoc.GetNumPages();
} if (beginPageNum > endPageNum)
{
throw new ArgumentException("参数\"beginPageNum\"必须小于\"endPageNum\"!");
} if (format == null)
{
format = ImageFormat.Png;
} if (zoom <= )
{
zoom = ;
} //转换
for (int i = beginPageNum; i <= endPageNum; i++)
{
//取出当前页
pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(i - );
//得到当前页的大小
pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
//生成一个页的裁剪区矩形对象
pdfRect = (Acrobat.CAcroRect)Microsoft.VisualBasic.Interaction.CreateObject("AcroExch.Rect", ""); //计算当前页经缩放后的实际宽度和高度,zoom==1时,保持原比例大小
int imgWidth = (int)((double)pdfPoint.x * zoom);
int imgHeight = (int)((double)pdfPoint.y * zoom); //设置裁剪矩形的大小为当前页的大小
pdfRect.Left = ;
pdfRect.right = (short)imgWidth;
pdfRect.Top = ;
pdfRect.bottom = (short)imgHeight; //将当前页的裁剪区的内容编成图片后复制到剪贴板中
pdfPage.CopyToClipboard(pdfRect, , , (short)( * zoom)); IDataObject clipboardData = Clipboard.GetDataObject(); //检查剪贴板中的对象是否是图片,如果是图片则将其保存为指定格式的图片文件
if (clipboardData.GetDataPresent(DataFormats.Bitmap))
{
Bitmap pdfBitmap = (Bitmap)clipboardData.GetData(DataFormats.Bitmap); pdfBitmap.Save(
Path.Combine(imageDirectoryPath, i.ToString("") + "." + format.ToString()), format); pdfBitmap.Dispose();
}
} //关闭和释放相关COM对象
pdfDoc.Close();
Marshal.ReleaseComObject(pdfRect);
Marshal.ReleaseComObject(pdfPoint);
Marshal.ReleaseComObject(pdfPage);
Marshal.ReleaseComObject(pdfDoc); }

三、第三方组件

其他参考:

C#实现MS-Office文档转Pdf(Word、Execel、PowerPoint、Visio、Project)

用C#实现Word,PPT,EXECL 图片输出

PDF/WORD/EXCEL 图片预览的更多相关文章

  1. Word/Excel 在线预览

    前言 近日项目中做到一个功能,需要上传附件后能够在线预览.之前也没做过这类似的,于是乎就查找了相关资料,.net实现Office文件预览大概有这几种方式: ① 使用Microsoft的Office组件 ...

  2. Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结

    Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word  excel pdf 的web预览要求 ...

  3. 在线操作word和在线预览查找的资料记录

    在线操作word和在线预览查找的资料记录 在线操作word查找的资料记录 富文本操作 http://fex.baidu.com/ueditor/ 控件类 通过 js 调用控件操作 word 文档 1. ...

  4. dropzonejs中文翻译手册 DropzoneJS是一个提供文件拖拽上传并且提供图片预览的开源类库.

    http://wxb.github.io/dropzonejs.com.zh-CN/dropzonezh-CN/ 由于项目需要,完成一个web的图片拖拽上传,也就顺便学习和了解了一下前端的比较新的技术 ...

  5. DropzoneJS是一个提供文件拖拽上传并且提供图片预览的开源类库.

    DropzoneJS是一个提供文件拖拽上传并且提供图片预览的开源类库. 它是轻量级的,不依赖任何其他类库(如JQuery)并且高度可定制. 试试看! 将文件拖至此处或点击上传.(这仅仅是 dropzo ...

  6. JS魔法堂之实战:纯前端的图片预览

    一.前言 图片上传是一个普通不过的功能,而图片预览就是就是上传功能中必不可少的子功能了.在这之前,我曾经通过订阅input[type=file]元素的onchange事件,一旦更改路径则将图片上传至服 ...

  7. js实现图片预览

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  8. 普通图片预览及demo(非分块)

    演示地址: http://codeman35.itongyin.com:19003/v2/image.html 功能:通过加载大图预览,这种方式无法和google art 比较.只能应用于简单的图片预 ...

  9. html5 图片上传,支持图片预览、压缩、及进度显示,兼容IE6+及标准浏览器

    以前写过上传组件,见 打造 html5 文件上传组件,实现进度显示及拖拽上传,兼容IE6+及其它标准浏览器,对付一般的上传没有问题,不过如果是上传图片,且需要预览的话,就力有不逮了,趁着闲暇时间,给上 ...

随机推荐

  1. 11个好用的jQuery拖拽拖放插件

    这次我们整理一些拖拽播放类型的jQuery插件,这些可能不是很常用,但偶尔会有网站设计项目用到,特别是后台相关的开发项目,这个拖放排序功能一般都会有,所以适合大家收藏起来,方便日后使用.接下来一起看盾 ...

  2. VS2005中SetUnhandledExceptionFilter函数应用

    很多软件通过设置自己的异常捕获函数,捕获未处理的异常,生成报告或者日志(例如生成mini-dump文件),达到Release版本下追踪Bug的目的.但是,到了VS2005(即VC8),Microsof ...

  3. WinAPI你知道多少?!(上千个,好多都没见过)

    http://www.cnblogs.com/vanver/archive/2013/06/13/NO-2013_06_13pm.html 播客开篇,讲讲废话:本篇播客只是推荐给热与钻研的同学们... ...

  4. ERDAS IMAGINE 9.2安装破解方法

    Install the application. Copy the license.dat and ERDAS.exe to C:\Program Files\Leica Geosystems\Sha ...

  5. Git教程之远程仓库(9)

    有个叫GitHub的神奇的网站,呵呵,从名字就可以看出,这个网站就是提供Git仓库托管服务的,所以,只要注册一个GitHub账号,就可以免费获得Git远程仓库. 由于本地Git仓库和GitHub仓库之 ...

  6. 213. House Robber II

    题目: Note: This is an extension of House Robber. After robbing those houses on that street, the thief ...

  7. Revit 二次开发 沿弧形路径创建拉伸屋顶

    沿弧形路径创建拉伸屋顶 Revit的API中只能按照直线创建拉伸屋顶,不能按照曲线创建拉伸屋顶.在Revit的界面当中,可以用 构建->内建模型,进行放样创建屋顶.但是没有办法代码内建模型. 可 ...

  8. (转) MFC的入口点与消息循环,消息映射

    博文分析的很不错,尤其是替换默认窗口过程的这块,本人觉得,所有的这些都可以参阅侯杰的<深入浅出MFC >. 来自:http://blog.csdn.net/sryan/article/de ...

  9. matlab 在代码中,显示错误,退出程序

    使用函数error('message_id', 'message'),出现错误时函数中止运行. 参考http://www.ilovematlab.cn/thread-43261-1-1.html

  10. 浩顺AC671指纹考勤机二次开发(demo)

    关于考勤机 AC671,是新换的机器,以前的那部机器,通过网络死活连接不上,换了AC671网络连接是好用了.但是,我要吐槽 浩顺的考勤机应该是卖了很多了吧,可是自带的软件太不给力,最后分析出来的数据一 ...