将pdf、doc、docx、ppt格式文件转化swf格式文件的方法
如果把pdf,doc、docx、ppt格式文件直接转化为swf格式,总会出这样那样的问题,有的会出乱码,有的原文中的图片会丢失,而且有多方法配置起来非常麻烦,经过我的多次实践摸索,终于找到一个比较完美的解决方案:那就是先把pdf等文档先转化成图片,再把图片转化为swf文件,话不多说直接上代码:
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Diagnostics;
using Microsoft.Office;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using O2S.Components.PDFRender4NET;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using Aspose.Words;
using Aspose.Words.Saving;
namespace CommTool
{
public class FileFormatHelper
{
private FileFormatHelper()
{
}
/*
/// <summary>
/// 把Microsoft.Office.Interop.Excel文件转换成PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public static bool ExcelToPDF(string sourcePath, string targetPath)
{
bool result = false;
Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.ApplicationClass application = null;
Microsoft.Office.Interop.Excel.Workbook workBook = null;
try
{
application = new Microsoft.Office.Interop.Excel.ApplicationClass();
application.Visible = false;
workBook = application.Workbooks.Open(sourcePath);
workBook.SaveAs();
workBook.ExportAsFixedFormat(targetType, targetPath);
result = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
result = false;
}
finally
{
if (workBook != null)
{
workBook.Close(true, missing, missing);
workBook = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}
*/
/// <summary>
/// 把PowerPoint文件转换成PDF格式文件
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
/*
public static bool PowerPointToPDF(string sourcePath, string targetPath)
{
bool result;
Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType targetFileType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF;
object missing = Type.Missing;
Microsoft.Office.Interop.PowerPoint.ApplicationClass application = null;
Microsoft.Office.Interop.PowerPoint.Presentation persentation = null;
try
{
application = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
//application.Visible = MsoTriState.msoFalse;
persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
result = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
result = false;
}
finally
{
if (persentation != null)
{
persentation.Close();
persentation = null;
}
if (application != null)
{
application.Quit();
application = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
}
*/
/// <summary>
/// 把PDF文件转化为SWF文件
/// </summary>
/// <param name="toolPah">pdf2swf工具路径</param>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转化成功</returns>
public static bool PDFToSWF(string toolPah, string sourcePath, string targetPath)
{
Process pc = new Process();
bool returnValue = true;
string cmd = toolPah;
string args = " -t " + sourcePath + " -s flashversion=9 -o " + targetPath + " languagedir=c:\\xpdf\\chinese-simplified";
// string args = " -t " + sourcePath + " -s flashversion=9 -o " + targetPath+" languagedir= E:\\开发\\EworksCms\\EworksCms.Web\\ConvertToSwfTool\\xpdf";
try
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.WindowStyle = ProcessWindowStyle.Hidden;
pc.StartInfo = psi;
pc.Start();
pc.WaitForExit();
}
catch (Exception ex)
{
returnValue = false;
throw new Exception(ex.Message);
}
finally
{
pc.Close();
pc.Dispose();
}
return returnValue;
}
/// <summary>
/// png、jpg和jpeg文件的转化
/// </summary>
/// <param name="toolPah"></param>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
public static bool PicturesToSwf(string toolPah, string sourcePath, string targetPath)
{
Process pc = new Process();
bool returnValue = true;
string cmd = toolPah;
string args = " " + sourcePath + " -o " + targetPath + " -T 9 ";
//如果是多个图片转化为swf 格式为 ..jpeg2swf.exe C:\1.jpg C:\2.jpg -o C:\swf1.swf
try
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.WindowStyle = ProcessWindowStyle.Hidden;
pc.StartInfo = psi;
pc.Start();
pc.WaitForExit();
}
catch (Exception ex)
{
returnValue = false;
throw new Exception(ex.Message);
}
finally
{
pc.Close();
pc.Dispose();
}
return returnValue;
}
/// <summary>
/// Gif文件转化为swf
/// </summary>
/// <param name="toolPah"></param>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
public static bool GifPicturesToSwf(string toolPah, string sourcePath, string targetPath)
{
Process pc = new Process();
bool returnValue = true;
string cmd = toolPah;
string args = " " + sourcePath + " -o " + targetPath;
try
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.WindowStyle = ProcessWindowStyle.Hidden;
pc.StartInfo = psi;
pc.Start();
pc.WaitForExit();
}
catch (Exception ex)
{
returnValue = false;
throw new Exception(ex.Message);
}
finally
{
pc.Close();
pc.Dispose();
}
return returnValue;
}
#region
//根目录
//语言包路径
private static string XPDF_LANG_PATH = "C:\\xpdf\\chinese-simplified";
#endregion
///
/// 运行Cmd命令
///
///命令字符串
///命令运行时间
public static double RunShell(string strShellCommand)
{
double spanMilliseconds = 0;
DateTime beginTime = DateTime.Now;
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.Arguments = String.Format(@"/c {0}", strShellCommand);
cmd.Start();
cmd.WaitForExit();
cmd.Close();
DateTime endTime = DateTime.Now;
TimeSpan timeSpan = endTime - beginTime;
spanMilliseconds = timeSpan.TotalMilliseconds;
return spanMilliseconds;
}
/// <summary>
/// 将PDF文档转换为图片
/// </summary>
/// <param name="pdfInputPath">PDF文件路径</param>
/// <param name="imageOutputPath">图片输出路径</param>
/// <param name="imageName">生成图片的名字</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
/// <param name="imageFormat">设置所需图片格式</param>
/// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
{
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
if (!Directory.Exists(imageOutputPath))
{
Directory.CreateDirectory(imageOutputPath);
}
// validate pageNum
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > pdfFile.PageCount)
{
endPageNum = pdfFile.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
string imagefile = imageOutputPath + imageName + "" + i + "." + imageFormat.ToString();
pageImage.Save(imagefile, imageFormat);
pageImage.Dispose();
}
pdfFile.Dispose();
}
/// <summary>
/// 将PDF文档转换为图片
/// </summary>
/// <param name="pdfInputPath">PDF文件路径</param>
/// <param name="imageOutputPath">图片输出路径</param>
/// <param name="imageName">生成图片的名字</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
/// <param name="imageFormat">设置所需图片格式</param>
/// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
public static string PDF2Image(string pdfInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
{
StringBuilder imagestr = new StringBuilder("");
if (File.Exists(pdfInputPath))
{
try
{
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
if (!Directory.Exists(imageOutputPath))
{
Directory.CreateDirectory(imageOutputPath);
}
// validate pageNum
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > pdfFile.PageCount)
{
endPageNum = pdfFile.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}
// string [] imagarr=new string[endPageNum];
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)Definition.Seven);
string imagefile = imageOutputPath + imageName + "" + Guid.NewGuid().ToString() + "." + imageFormat.ToString();
pageImage.Save(imagefile, imageFormat);
pageImage.Dispose();
// imagarr[i-1] = imagefile;
imagestr.Append(imagefile + " ");
}
}
catch (Exception)
{
imagestr.Append("");
}
}
return imagestr.ToString();
}
/// <summary>
/// 将PDF文档转换为图片的方法
/// </summary>
/// <param name="pdfInputPath">PDF文件路径</param>
public static string ConvertPDFToImage(string pdfInputPath)
{
string ImageFullName = string.Empty;
// string imagefilename = string.Empty;
if (File.Exists(pdfInputPath))
{
int extentionIndex = pdfInputPath.ToLower().IndexOf(".pdf");
string realpath = pdfInputPath.Substring(0, extentionIndex);
try
{
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
// start to convert
Bitmap pageImage = pdfFile.GetPageImage(0, 56 * (int)Definition.Seven);
string imagefilename = realpath + "." + ImageFormat.Jpeg.ToString();
pageImage.Save(imagefilename, ImageFormat.Jpeg);
string imgname = imagefilename.Split('\\')[imagefilename.Split('\\').Length - 1].ToString();
ImageFullName = imgname;
pageImage.Dispose();
pdfFile.Dispose();
}
catch (Exception)
{
ImageFullName = string.Empty;
}
}
return ImageFullName;
// return imagefilename;
}
public enum Definition
{
One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
}
/// <summary>
/// 将Word文档转换为图片的方法(该方法基于第三方DLL),你可以像这样调用该方法:
/// ConvertPDF2Image("F:\\PdfFile.doc", "F:\\", "ImageFile", 1, 20, ImageFormat.Png, 256);
/// </summary>
/// <param name="pdfInputPath">Word文件路径</param>
/// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param>
/// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为Word的名称</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public static string ConvertWordToImage(string wordInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution)
{
StringBuilder imagestr = new StringBuilder("");
if (File.Exists(wordInputPath))
{
try
{
// open word file
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
// validate parameter
if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
if (imageOutputPath.Trim().Length == 0) { imageOutputPath = Path.GetDirectoryName(wordInputPath); }
if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
if (imageName.Trim().Length == 0) { imageName = Path.GetFileNameWithoutExtension(wordInputPath); }
if (startPageNum <= 0) { startPageNum = 1; }
if (endPageNum > doc.PageCount || endPageNum <= 0) { endPageNum = doc.PageCount; }
if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; }
if (imageFormat == null) { imageFormat = ImageFormat.Png; }
if (resolution <= 0) { resolution = 128; }
ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat));
imageSaveOptions.Resolution = resolution;
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
imageSaveOptions.PageIndex = i - 1;
// string filepath = Path.Combine(imageOutputPath, imageName) + "_" + Guid.NewGuid().ToString() + "." + imageFormat.ToString();
string filepath = imageOutputPath + imageName + "" + Guid.NewGuid().ToString() + "." + imageFormat.ToString();
doc.Save(filepath, imageSaveOptions);
imagestr.Append(filepath + " ");
}
}
catch (Exception ex)
{
throw ex;
}
}
return imagestr.ToString();
}
private static SaveFormat GetSaveFormat(ImageFormat imageFormat)
{
SaveFormat sf = SaveFormat.Unknown;
if (imageFormat.Equals(ImageFormat.Png))
sf = SaveFormat.Png;
else if (imageFormat.Equals(ImageFormat.Jpeg))
sf = SaveFormat.Jpeg;
else if (imageFormat.Equals(ImageFormat.Tiff))
sf = SaveFormat.Tiff;
else if (imageFormat.Equals(ImageFormat.Bmp))
sf = SaveFormat.Bmp;
else
sf = SaveFormat.Unknown;
return sf;
}
public static string PptToImg(string pptPath, string imgPath)
{
var app = new Microsoft.Office.Interop.PowerPoint.Application();
var ppt = app.Presentations.Open(pptPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
var index = 0;
// var fileName = Path.GetFileNameWithoutExtension(pptPath);
StringBuilder imagestr = new StringBuilder("");
string gid = "";
foreach (Microsoft.Office.Interop.PowerPoint.Slide slid in ppt.Slides)
{
gid = Guid.NewGuid().ToString();
++index;
//设置图片大小
slid.Export(imgPath + string.Format("page{0}.jpg", gid), "jpg", 1024, 768);
imagestr.Append(imgPath + "page" + gid + ".jpg ");
//根据屏幕尺寸。设置图片大小
// slid.Export(imgPath+string.Format("page{0}.jpg",index.ToString()), "jpg", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}
//释放资源
ppt.Close();
app.Quit();
GC.Collect();
return imagestr.ToString();
}
}
}
要注意的是这段代码引用了两个插件类库:Aspose.Words.dll,O2S.Components.PDFRender4NET.dll可以在网上搜索找到。