net 预览文件 转换文件
预览SWF文件
swfobject.js (google浏览器 会阻止 需设置)
@{
ViewBag.Title = "PdfPreview";
Layout = "~/Views/Shared/_Layout.cshtml";
var fileType = ViewBag.fileType;
var swfpath = ViewBag.filePath;
} <script src="~/Content/js/jquery.uploadify/swfobject.js"></script>
<script src="~/Content/js/jquery.uploadify/flexpaper_flash_debug.js"></script> <script src="/Content/js/jquery.uploadify/jquery-1.4.1.min.js"></script>
<div id="app">
<div id="contentText" style="border: dashed 1px #dddddd; background-color: white;">
<div id="flashContent">
</div>
</div>
</div> <script type="text/javascript">
var swfVersionStr = "10.0.0";
var swf = "@swfpath";
//var swf = "http://localhost:8080/tmp/94D1390E-930D-4D41-BD88-72FDC3273755/94D1390E-930D-4D41-BD88-72FDC3273755.pdf";
//var swf = "C:/Users/zz/Desktop/File/1.pdf";
if (swf != "") {
var swfpath = swf.replace('docx', 'swf').replace('xlsx', 'swf').replace('xls', 'swf').replace('doc', 'swf').replace("pdf", "swf");
var xiSwfUrlStr = "playerProductInstall.swf";
var swfFile = swfpath; var flashvars = {
SwfFile: escape(swfFile),//编码设置
Scale: 0.6,
ZoomTransition: "easeOut",//变焦过渡
ZoomTime: 0.5,
ZoomInterval: 0.2,//缩放滑块-移动的缩放基础[工具栏]
FitPageOnLoad: true,//自适应页面
FitWidthOnLoad: true,//自适应宽度
PrintEnabled: true,//是否启用打印
FullScreenAsMaxWindow: false,//全屏按钮-新页面全屏[工具栏]
ProgressiveLoading: true,//分割加载
//MinZoomSize: 0.2,//最小缩放
//MaxZoomSize: 3,//最大缩放
PrintToolsVisible: true,//是否显示打印工具
ViewModeToolsVisible: true,//显示模式工具栏是否显示
ZoomToolsVisible: true,//缩放工具栏是否显示
FullScreenVisible: true,//是否全屏
NavToolsVisible: true,//跳页工具栏
CursorToolsVisible: true,
SearchMatchAll: true,//搜索匹配全部
SearchToolsVisible: true,//是否显示搜索工具
localeChain: "zh_CN"//语言
}; var params = {
} params.quality = "high";
params.bgcolor = "#ffffff";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "FlexPaperViewer";
attributes.name = "FlexPaperViewer";
swfobject.embedSWF(
"/Content/js/jquery.uploadify/FlexPaperViewer.swf",//默认显示的swfUrl
"flashContent",//展示区域Id
"100%",//展示宽度
(window.innerHeight - ) + "px",//战术高度
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent",//展示区域Id
"display:block;text-align:center;"); //滚动条监听
window.onload = function () {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', deltaDispatcher, false);
}
document.body.onmousewheel = deltaDispatcher;
}
function deltaDispatcher(event) {
event = window.event || event;
var delta = ;
if (event.wheelDelta) {
delta = event.wheelDelta / ;
if (window.opera) {
delta = -delta;
}
} else if (event.detail) {
delta = -event.detail;
}
if (event.preventDefault) {
event.preventDefault();
}
var obj = swfobject.getObjectById("FlexPaperViewer");
if (typeof (obj.externalMouseEvent) == 'function') {
obj.externalMouseEvent(delta);
}
}
}
</script>
预览音频 视频 图片
@{
ViewBag.Title = "文件预览";
Layout = "~/Views/Shared/_Layout.cshtml";
var fileType = ViewBag.fileType;
var filePath = ViewBag.filePath;
} <div id="app">
<el-container id="filePreview">
@*(因为可能不支持vue动态绑定,所以改成js动态加载)*@ @*<audio v-bind:style="{ 'display':preview.audioShow}" controls>
<source :src="preview.audioUrl" type="audio/mpeg">
<source :src="preview.audioUrl" type="audio/ogg">
<embed height="" width="" :src="preview.audioUrl">
</audio>*@@*//音频*@ @*<video v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%','display':preview.videoShow}" controls autoplay>
<source :src="preview.videoUrl" type="video/ogg">
<source :src="preview.videoUrl" type="video/mp4">
<source :src="preview.videoUrl" type="video/webm">
<object :data="preview.videoUrl" v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%'}">
<embed v-bind:style="{ 'height': mainHeight - 17 + 'px','width':'100%'}" :src="preview.videoUrl">
</object>
</video>*@@*//视频*@ @*<img :src="preview.imgUrl" :style="{ 'display':preview.imgShow}" />*@@*//图片*@
</el-container>
</div> <script>
var app = new Vue({
el: "#app",
data: {
mainHeight: window.innerHeight,
preview: {
fileUrl: "",
audioUrl: "",
videoUrl: "",
imgUrl: "",
fileShow: "none",
audioShow: "none",
videoShow: "",
imgShow: "none"
},
},
mounted: function () {
const cur = this;
window.onload = () => {
cur.pageLoad();
};
window.onresize = () => {
cur.mainHeight = window.innerHeight;
}
},
methods: {
pageLoad() {
const cur = this;
let fileType = "@fileType";//文件类型
let filePath = "@filePath";//预览URL
cur.preview = {
audioUrl: "",
videoUrl: "",
imgUrl: "",
audioShow: "none",
videoShow: "none",
imgShow: "none"
};
var filePreview = document.getElementById("filePreview");
var str = "";
switch (fileType) { case ""://视频
//cur.preview = {
// audioUrl: "",
// videoUrl: filePath,
// imgUrl: "",
// audioShow: "none",
// videoShow: "",
// imgShow: "none"
//};
str = "<video style='width:100%; height:" + (cur.mainHeight - ) + "px;' controls autoplay>";
str += "< source src = '" + filePath + "' type = 'video/ogg' >";
str += "<source src='" + filePath + "' type='video/mp4'>";
str += "<source src='" + filePath + "' type='video/webm'>";
str += "<object data='" + filePath + "' style='width:100%; height:" + (cur.mainHeight - ) + "px;'>";
str += "<embed style='width:100%; height:" + (cur.mainHeight - ) + "px;' src='" + filePath + "'>";
str += "</object></video>";
break;
case "2-1"://图片
case ""://图片
//cur.preview = {
// audioUrl: "",
// videoUrl: "",
// imgUrl: filePath,
// audioShow: "none",
// videoShow: "none",
// imgShow: ""
//};
str = "<img src=\"" + filePath + "\" />";
break;
case ""://音频
//cur.preview = {
// audioUrl: filePath,
// videoUrl: "",
// imgUrl: "",
// audioShow: "",
// videoShow: "none",
// imgShow: "none"
//};
str = "<audio controls='controls'>";
str += "<source src = '" + filePath + "' type = 'audio/mpeg' >";
str += "<source src='" + filePath + "' type='audio/ogg'>";
str += "<object height='50' width='100' data='" + filePath + "'>";
str += "<embed height='50' width='100' src='" + filePath + "'>";
str += "</object></audio>";
break;
default:
break;
}
filePreview.innerHTML = str;
},
}
});
</script>
后端:
1.返回定义好的文件类型
private string[] imgExts = new string[] { ".BMP", ".GIF", ".JPEG", ".JPG", ".PNG", ".TIFF", ".TIF" }; //转换文件类型
result.Data.RelativePaths = (HttpContext.Current.Request.Url.Authority + "\\" + Index(result.Data.RelativePaths)).Replace("\\", "/");
string fileext = Util.GetFileExt(doc.DocName).ToLower();
if (imgExts.Contains(fileext.ToUpper()))//图片
{
if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
{
result.Data.DocType = "2-2";//图片-swf
}
else
{
result.Data.DocType = "2-1";//图片
}
}
else if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(fileext))//音频
{
result.Data.DocType = "";
}
else if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(fileext))//视频
{
result.Data.DocType = "";
}
else if (".doc;.docx".Contains(fileext))//word
{
if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html")
{
result.Data.DocType = "4-1";//word-html
}
else
{
result.Data.DocType = "4-2";//word-swf
} }
else if (".xls;.xlsx".Contains(fileext))//excel
{
if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".html")
{
result.Data.DocType = "5-1";//excel-html
}
else
{
result.Data.DocType = "5-2";//excel-swf
}
}
else if (".txt".Contains(fileext))//文本
{
if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
{
result.Data.DocType = "6-2";
}
else
{
result.Data.DocType = "6-1";
}
}
else if (".html;.htm".Contains(fileext))//网页
{
if (Util.GetFileExt(result.Data.RelativePaths).ToLower() == ".swf")
{
result.Data.DocType = "7-2";//网页-swf
}
else
{
result.Data.DocType = "7-1";//网页
}
}
else if (".pdf;.swf".Contains(fileext))//pdf
{
result.Data.DocType = "";
}
}
catch (Exception ex)
{
Logger.Error(ex);
result.ErrCode = ;
result.ResultMsg = "获取文件失败!";
}
return result;
2.转换文件
/// <summary>
/// 返回本地文件或共享文件
/// </summary>
/// <param name="path">相对路径</param>
/// <param name="serverPath">共享服务器</param>
/// <returns></returns>
public string MapPath(string path, string serverPath = "")
{
string ph = path;
if (string.IsNullOrWhiteSpace(path)) return "";
string url = ConfigHelper.GetValue("ShareFileUrl"); if (!string.IsNullOrEmpty(serverPath))
{
url = serverPath;
} //共享文件夹能够连接
if (ConnectShareFileSys())
{
ph = path.Replace("~", url).Replace("/", "\\");
}
else
{
ph = HttpContext.Current.Server.MapPath(path);
} return ph;
} /// <summary>
/// 获取客户端IP地址
/// </summary>
/// <returns></returns>
public string GetIP()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (string.IsNullOrEmpty(result))
{
return "127.0.0.1";
}
return result;
} #region Index页面
/// <summary>
/// Index页面
/// </summary>
/// <param name="url">例:/uploads/......XXX.xls</param>
public string Index(string url)
{
if (string.IsNullOrWhiteSpace(url)) return "";
string physicalPath = AppDomain.CurrentDomain.BaseDirectory + url;
string extension = Path.GetExtension(physicalPath);
string htmlUrl = "";
if (imgExts.Contains(extension.ToUpper()))//图片
{
htmlUrl = PreviewPicture(physicalPath, url);
return htmlUrl;
}
if (".wav;.mp3;.ra;.rma;.wma;.asf;.mid;.midi;.rmi;.xmi;.ogg;.vqf;.tvq;.mod;.ape;.aiff;.au".Contains(extension.ToLower()))//音频
{
htmlUrl = PreviewAudio(physicalPath, url);
return htmlUrl;
}
if (".m4a;.wma;.rm;.midi;.ape;.flac;.avi;.rmvb;.asf;.divx;.mpg;.mpeg;.mpe;.wmv;.mp4;.mkv;.vob".Contains(extension.ToLower()))//视频
{
htmlUrl = PreviewVideo(physicalPath, url);
return htmlUrl;
}
switch (extension.ToLower())
{
case ".xls":
case ".xlsx":
htmlUrl = PreviewExcel(physicalPath, url);
break;
case ".doc":
case ".docx":
htmlUrl = PreviewWord(physicalPath, url);
break;
case ".txt":
htmlUrl = PreviewTxt(physicalPath, url);
break;
case ".pdf":
case ".swf":
htmlUrl = PreviewPdf(physicalPath, url);
break;
case ".html":
case ".htm":
htmlUrl = PreviewHtml(physicalPath, url);
break;
}
return htmlUrl;
}
#endregion
#region 预览Excel
/// <summary>
/// 预览Excel
/// </summary>
/// <param name="physicalPath">绝对路径</param>
/// <param name="url">相对路径</param>
/// <returns></returns>
public string PreviewExcel(string physicalPath, string url)
{
string pdfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".pdf";
if (!File.Exists(pdfPath))
{
if (ExcelToPdf(physicalPath, pdfPath))//转换成pdf
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
else//转换成html
{
return ExcelToHtml(physicalPath, url);
}
}
else
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
}
/// <summary>
/// 预览Excel转换成html(备用)
/// </summary>
/// <param name="physicalPath">绝对路径</param>
/// <param name="url">相对路径</param>
/// <returns></returns>
public string ExcelToHtml(string physicalPath, string url)
{
Excel.Application application = null;
Excel.Workbook workbook = null;
application = new Excel.Application();
object missing = Type.Missing;
object trueObject = true;
application.Visible = false;
application.DisplayAlerts = false;
workbook = application.Workbooks.Open(physicalPath, missing, trueObject, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
//Save Excel to Html
object format = Excel.XlFileFormat.xlHtml;
string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
workbook.SaveAs(outputFile, format, missing, missing, missing,
missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,
missing, missing, missing, missing);
workbook.Close();
application.Quit();
return Path.GetDirectoryName(url) + "\\" + htmlName;
}
/// <summary>
/// 把Excel文件转换成PDF格式文件(office)
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public bool XLSConvertToPDF(string sourcePath, string targetPath)
{
bool result = false;
Excel.XlFixedFormatType targetType = Excel.XlFixedFormatType.xlTypePDF;
object missing = Type.Missing;
Excel.ApplicationClass application = null;
//Excel.Application application = null;//如不支持换上面注释代码
Excel.Workbook workBook = null;
try
{
application = new Excel.ApplicationClass();
//application = new Excel.Application();//如不支持换上面注释代码
object target = targetPath;
object type = targetType;
workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing); workBook.ExportAsFixedFormat(targetType, target, Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
result = true;
}
catch
{
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>
/// 把Excel文件转换成PDF格式文件(Aspose)
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
public bool ExcelToPdf(string sourcePath, string targetPath)
{
bool result = false;
try
{
//Excel
Workbook excel = new Workbook(sourcePath);
excel.Save(targetPath, Aspose.Cells.SaveFormat.Pdf);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
#endregion
#region 预览Word
/// <summary>
/// 预览Word
/// </summary>
/// <param name="physicalPath">绝对路径</param>
/// <param name="url">相对路径</param>
/// <returns></returns>
public string PreviewWord(string physicalPath, string url)
{
string pdfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".pdf";
if (!File.Exists(pdfPath))
{
if (WordToPdf(physicalPath, pdfPath))//转换成pdf
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
else//转换成html
{
return WordToHtml(physicalPath, url);
}
}
else
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
}
/// <summary>
/// 预览Word转换成html(备用)
/// </summary>
/// <param name="physicalPath">绝对路径</param>
/// <param name="url">相对路径</param>
/// <returns></returns>
public string WordToHtml(string physicalPath, string url)
{
Word._Application application = null;
Word._Document doc = null;
application = new Word.Application();
object missing = Type.Missing;
object trueObject = true;
application.Visible = false;
application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
doc = application.Documents.Open(physicalPath, missing, trueObject, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//Save Excel to Html
object format = Word.WdSaveFormat.wdFormatHTML;
string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
doc.SaveAs(outputFile, format, missing, missing, missing,
missing, Excel.XlSaveAsAccessMode.xlNoChange, missing,
missing, missing, missing, missing);
doc.Close();
application.Quit();
return Path.GetDirectoryName(url) + "\\" + htmlName;
}
//Word转换成pdf
/// <summary>
/// 把Word文件转换成为PDF格式文件(office)
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
private bool DOCConvertToPDF(string sourcePath, string targetPath)
{
bool result = false;
Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF;
object paramMissing = Type.Missing;
Word.ApplicationClass wordApplication = new Word.ApplicationClass();
//Word.Application wordApplication = new Word.Application();//如不支持换上面注释代码
Word.Document wordDocument = null;
try
{
object paramSourceDocPath = sourcePath;
string paramExportFilePath = targetPath; Word.WdExportFormat paramExportFormat = exportFormat;
bool paramOpenAfterExport = false;
Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
int paramStartPage = ;
int paramEndPage = ;
Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
bool paramIncludeDocProps = true;
bool paramKeepIRM = true;
Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
bool paramDocStructureTags = true;
bool paramBitmapMissingFonts = true;
bool paramUseISO19005_1 = false; wordDocument = wordApplication.Documents.Open(
ref paramSourceDocPath, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing); if (wordDocument != null)
wordDocument.ExportAsFixedFormat(paramExportFilePath,
paramExportFormat, paramOpenAfterExport,
paramExportOptimizeFor, paramExportRange, paramStartPage,
paramEndPage, paramExportItem, paramIncludeDocProps,
paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
paramBitmapMissingFonts, paramUseISO19005_1,
ref paramMissing);
result = true;
}
catch
{
result = false;
}
finally
{
if (wordDocument != null)
{
wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
wordDocument = null;
}
if (wordApplication != null)
{
wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
wordApplication = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
return result;
} /// <summary>
/// 把Word文件转换成为PDF格式文件(Aspose)
/// </summary>
/// <param name="sourcePath">源文件路径</param>
/// <param name="targetPath">目标文件路径</param>
/// <returns>true=转换成功</returns>
private bool WordToPdf(string sourcePath, string targetPath)
{
bool result = false;
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(sourcePath);
doc.Save(targetPath, Aspose.Words.SaveFormat.Pdf);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
#endregion
#region 预览Txt
/// <summary>
/// 预览Txt
/// </summary>
public string PreviewTxt(string physicalPath, string url)
{
string pdfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".pdf";
if (!File.Exists(pdfPath))//不存在pdf
{
if (TxtToPdf(physicalPath, pdfPath))//转换成功
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
else
{
return url;
}
}
else
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
}
/// <summary>
/// 把txt文件转换成pdf格式文件
/// </summary>
/// <param name="txtFile"></param>
/// <param name="pdfFile"></param>
/// <returns></returns>
public bool TxtToPdf(string txtFile, string pdfFile)
{
bool result = false;
try
{
//第一个参数是txt文件物理路径
string[] lines = System.IO.File.ReadAllLines(txtFile, Encoding.GetEncoding("gb2312"));
//iTextSharp.text.PageSize.A4 自定义页面大小
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, , , , );
PdfWriter pdfwriter =
PdfWriter.GetInstance(doc, new FileStream(pdfFile, FileMode.Create)); doc.Open();
//创建我的基本字体
BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//创建字体 字体大小,字体粗細 字体颜色
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, , iTextSharp.text.Font.NORMAL, BaseColor.BLACK); iTextSharp.text.Paragraph paragraph;
foreach (string line in lines)
{
paragraph = new iTextSharp.text.Paragraph(line, font);
doc.Add(paragraph);
} //关闭文件
doc.Close();
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
/// <summary>
/// 把txt文件转换成pdf格式文件(备用)
/// </summary>
/// <param name="txtFile"></param>
/// <param name="pdfFile"></param>
/// <returns></returns>
public bool TxtConvertPdf(string txtFile, string pdfFile)
{
bool result = false;
try
{
var document = new iTextSharp.text.Document(PageSize.A4, 30f, 30f, 30f, 30f);
PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
document.Open();
var bfSun = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
var font = new iTextSharp.text.Font(bfSun, 12f);
var objReader = new StreamReader(txtFile, Encoding.GetEncoding("gb2312"));
var str = "";
while (str != null)
{
str = objReader.ReadLine();
if (str != null)
{
document.Add(new iTextSharp.text.Paragraph(str, font));
}
}
objReader.Close();
document.Close();
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
#endregion
#region 预览图片
/// <summary>
/// 预览图片
/// </summary>
public string PreviewPicture(string physicalPath, string url)
{
string pdfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".pdf";
if (!File.Exists(pdfPath))//不存在转pdf
{
if (ConvertJPG2PDF(physicalPath, pdfPath))//转换成功
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
else
{
//预览图片
return url;
}
}
else
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
}
/// <summary>
/// 把图片转换pdf格式文件
/// </summary>
/// <param name="jpgfile"></param>
/// <param name="pdf"></param>
/// <returns></returns>
public bool ConvertJPG2PDF(string jpgfile, string pdf)
{
bool result = false;
try
{
var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, , , , );
using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfWriter.GetInstance(document, stream);
document.Open();
using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var image = Image.GetInstance(imageStream);
if (image.Height > iTextSharp.text.PageSize.A4.Height - )
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - , iTextSharp.text.PageSize.A4.Height - );
}
else if (image.Width > iTextSharp.text.PageSize.A4.Width - )
{
image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - , iTextSharp.text.PageSize.A4.Height - );
}
image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
document.Add(image);
} document.Close();
}
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
#endregion
#region 预览Pdf
/// <summary>
/// 预览Pdf
/// </summary>
public string PreviewPdf(string physicalPath, string url)
{
if (Util.GetFileExt(physicalPath).ToLower() == ".swf")
{
return url;
}
string swfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".swf";
if (!File.Exists(swfPath))
{
Pdf2Swf(physicalPath, swfPath);
}
return url.Substring(, url.LastIndexOf('.')) + ".swf";
} //pwf2swf.exe 文件所在目录
private string Pdf2Swfexe = Util.BaseDirectory.TrimEnd('\\') + @"\Tools\pdf2swf\pdf2swf.exe"; /// <summary>
/// 转换所有的页,图片质量80%
/// </summary>
/// <param name="pdfPath">PDF文件地址</param>
/// <param name="swfPath">生成后的SWF文件地址</param>
public bool Pdf2Swf(string pdfPath, string swfPath)
{
return Pdf2Swf(pdfPath, swfPath, , GetPageCount(pdfPath), );
} /// <summary>
/// PDF格式转为SWF
/// </summary>
/// <param name="pdfPath">PDF文件地址</param>
/// <param name="swfPath">生成后的SWF文件地址</param>
/// <param name="beginpage">转换开始页</param>
/// <param name="endpage">转换结束页</param>
/// <param name="photoQuality"></param>
private bool Pdf2Swf(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
{
if (!System.IO.File.Exists(Pdf2Swfexe) ||
!System.IO.File.Exists(pdfPath) ||
System.IO.File.Exists(swfPath))
{
return false;
} //执行的命令参数
StringBuilder command = new StringBuilder(); command.AppendFormat(" \"{0}\"", pdfPath);
command.AppendFormat(" -o \"{0}\"", swfPath);
command.Append(" -s flashversion=9");
command.AppendFormat(" -p \"{0}-{1}\"", beginpage, endpage);
command.AppendFormat(" -j {0}", photoQuality); Process p = new Process
{
StartInfo =
{
FileName = Pdf2Swfexe,
Arguments = command.ToString(),
WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/"),
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
CreateNoWindow = false
}
};
p.Start();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
p.Dispose(); return true;
} /// <summary>
/// 取PDF总页数
/// </summary>
/// <param name="pdfPath">PDF文件地址</param>
private int GetPageCount(string pdfPath)
{
byte[] buffer = System.IO.File.ReadAllBytes(pdfPath); if (buffer.Length <= )
{
return -;
} string pdfText = Encoding.Default.GetString(buffer); Regex rx1 = new Regex(@"/Type\s*/Page[^s]");
MatchCollection matches = rx1.Matches(pdfText);
if (matches.Count == )
{
//iTextSharp读取pdf页数
PdfReader pdfReader = new PdfReader(pdfPath);
if (pdfReader.NumberOfPages == )
{
return ;
}
return pdfReader.NumberOfPages;
}
return matches.Count;
} #region 获取PDF文件的页数(废弃) private int BytesLastIndexOf(Byte[] buffer, int length, string Search)
{
if (buffer == null)
return -;
if (buffer.Length <= )
return -;
byte[] SearchBytes = Encoding.Default.GetBytes(Search.ToUpper());
for (int i = length - SearchBytes.Length; i >= ; i--)
{
bool bFound = true;
for (int j = ; j < SearchBytes.Length; j++)
{
if (ByteUpper(buffer[i + j]) != SearchBytes[j])
{
bFound = false;
break;
}
}
if (bFound)
return i;
}
return -;
} private byte ByteUpper(byte byteValue)
{
char charValue = Convert.ToChar(byteValue);
if (charValue < 'a' || charValue > 'z')
return byteValue;
else
return Convert.ToByte(byteValue - );
} /// <summary>
/// 获取pdf文件的页数
/// </summary>
public int GetPDFPageCount(string path) //获取pdf文件的页数
{
//path = HttpContext.Current.Server.MapPath(path);
byte[] buffer = File.ReadAllBytes(path);
int length = buffer.Length;
if (buffer == null)
return -;
if (buffer.Length <= )
return -;
try
{
//Sample
// 29 0 obj
// <</Count 9
// Type /Pages
int i = ;
int nPos = BytesLastIndexOf(buffer, length, "/Type/Pages");
if (nPos == -)
return -;
string pageCount = null;
for (i = nPos; i < length - ; i++)
{
if (buffer[i] == '/' && buffer[i + ] == 'C' && buffer[i + ] == 'o' && buffer[i + ] == 'u' && buffer[i + ] == 'n' && buffer[i + ] == 't')
{
int j = i + ;
while (buffer[j] != '/' && buffer[j] != '>')
j++;
pageCount = Encoding.Default.GetString(buffer, i, j - i);
break;
}
}
if (pageCount == null)
return -;
int n = pageCount.IndexOf("Count");
if (n > )
{
pageCount = pageCount.Substring(n + ).Trim();
for (i = pageCount.Length - ; i >= ; i--)
{
if (pageCount[i] >= '' && pageCount[i] <= '')
{
return int.Parse(pageCount.Substring(, i + ));
}
}
}
return -;
}
catch (Exception ex)
{
return -;
}
} #endregion
#endregion
#region 预览视频
/// <summary>
/// 预览视频
/// </summary>
public string PreviewVideo(string physicalPath, string url)
{
if (Util.GetFileExt(physicalPath).ToLower() == ".mp4")
{
return url;
}
string mp4Path = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".mp4";
if (!File.Exists(mp4Path))
{
ConvertToMp4(physicalPath, mp4Path);
}
return url.Substring(, url.LastIndexOf('.')) + ".mp4";
}
/// <summary>
/// 格式转换(Mp4)
/// </summary>
/// <param name="pathBefore">原格式文件路径(绝对路劲)</param>
/// <param name="pathLater">转换后文件路径(绝对路劲)</param>
/// <returns></returns>
public string ConvertToMp4(string pathBefore, string pathLater)
{
string c = Util.BaseDirectory.TrimEnd('\\') + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -y " + pathLater;
string str = RunCmd(c);
return str;
}
#endregion
#region 预览html
/// <summary>
/// 预览html
/// </summary>
public string PreviewHtml(string physicalPath, string url)
{
string pdfPath = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".pdf";
if (!File.Exists(pdfPath))//不存在
{
if (HtmlConvertToPdf(physicalPath, pdfPath))//转换成功
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
else
{
return url;
}
}
else
{
//预览pdf
return PreviewPdf(pdfPath, url.Substring(, url.LastIndexOf('.')) + ".pdf");
}
}
/// <summary>
/// HTML文本内容转换为PDF
/// </summary>
/// <param name="strHtml">HTML文本内容</param>
/// <param name="savePath">PDF文件保存的路径</param>
/// <returns></returns>
public bool HtmlTextConvertToPdf(string strHtml, string savePath)
{
bool flag = false;
try
{
string htmlPath = HtmlTextConvertFile(strHtml); flag = HtmlConvertToPdf(htmlPath, savePath);
File.Delete(htmlPath);
}
catch
{
flag = false;
}
return flag;
} /// <summary>
/// HTML转换为PDF
/// </summary>
/// <param name="htmlPath">可以是本地路径,也可以是网络地址</param>
/// <param name="savePath">PDF文件保存的路径</param>
/// <returns></returns>
public bool HtmlConvertToPdf(string htmlPath, string savePath)
{
bool flag = false;
CheckFilePath(savePath); ///这个路径为程序集的目录,因为我把应用程序 wkhtmltopdf.exe 放在了程序集同一个目录下
//string exePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "wkhtmltopdf.exe";
string exePath = Util.BaseDirectory.TrimEnd('\\') + @"\Tools\wkhtmltopdf\wkhtmltopdf.exe";
if (!File.Exists(exePath))
{
throw new Exception("No application wkhtmltopdf.exe was found.");
} try
{
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = exePath;
processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.Arguments = GetArguments(htmlPath, savePath); Process process = new Process();
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit(); ///用于查看是否返回错误信息
//StreamReader srone = process.StandardError;
//StreamReader srtwo = process.StandardOutput;
//string ss1 = srone.ReadToEnd();
//string ss2 = srtwo.ReadToEnd();
//srone.Close();
//srone.Dispose();
//srtwo.Close();
//srtwo.Dispose(); process.Close();
process.Dispose(); flag = true;
}
catch
{
flag = false;
}
return flag;
} /// <summary>
/// 获取命令行参数
/// </summary>
/// <param name="htmlPath"></param>
/// <param name="savePath"></param>
/// <returns></returns>
private string GetArguments(string htmlPath, string savePath)
{
if (string.IsNullOrEmpty(htmlPath))
{
throw new Exception("HTML local path or network address can not be empty.");
} if (string.IsNullOrEmpty(savePath))
{
throw new Exception("The path saved by the PDF document can not be empty.");
} StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(" --page-height 297 "); //页面高度297mm(A4纸高度)
stringBuilder.Append(" --page-width 210 "); //页面宽度210mm(A4纸宽度)
//stringBuilder.Append(" --header-center 我是页眉 "); //设置居中显示页眉
//stringBuilder.Append(" --header-line "); //页眉和内容之间显示一条直线
//stringBuilder.Append(" --footer-center \"Page [page] of [topage]\" "); //设置居中显示页脚
//stringBuilder.Append(" --footer-line "); //页脚和内容之间显示一条直线
stringBuilder.Append(" " + htmlPath + " "); //本地 HTML 的文件路径或网页 HTML 的URL地址
stringBuilder.Append(" " + savePath + " "); //生成的 PDF 文档的保存路径
return stringBuilder.ToString();
} /// <summary>
/// 验证保存路径
/// </summary>
/// <param name="savePath"></param>
private void CheckFilePath(string savePath)
{
string ext = string.Empty;
string path = string.Empty;
string fileName = string.Empty; ext = Path.GetExtension(savePath);
if (string.IsNullOrEmpty(ext) || ext.ToLower() != ".pdf")
{
throw new Exception("Extension error:This method is used to generate PDF files.");
} fileName = Path.GetFileName(savePath);
if (string.IsNullOrEmpty(fileName))
{
throw new Exception("File name is empty.");
} try
{
path = savePath.Substring(, savePath.IndexOf(fileName));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch
{
throw new Exception("The file path does not exist.");
}
} /// <summary>
/// HTML文本内容转HTML文件
/// </summary>
/// <param name="strHtml">HTML文本内容</param>
/// <returns>HTML文件的路径</returns>
public string HtmlTextConvertFile(string strHtml)
{
if (string.IsNullOrEmpty(strHtml))
{
throw new Exception("HTML text content cannot be empty.");
} try
{
string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"html\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(, ) + ".html";
FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.Default);
streamWriter.Write(strHtml);
streamWriter.Flush(); streamWriter.Close();
streamWriter.Dispose();
fileStream.Close();
fileStream.Dispose();
return fileName;
}
catch
{
throw new Exception("HTML text content error.");
}
}
#endregion
#region 预览音频
/// <summary>
/// 预览音频
/// </summary>
public string PreviewAudio(string physicalPath, string url)
{
if (Util.GetFileExt(physicalPath).ToLower() == ".mp3")
{
return url;
}
string mp3Path = physicalPath.Substring(, physicalPath.LastIndexOf('.')) + ".mp3";
if (!File.Exists(mp3Path))
{
ConvertToMp3(physicalPath, mp3Path);
}
return url.Substring(, url.LastIndexOf('.')) + ".mp3";
}
/// <summary>
/// 格式转换(Mp3)
/// </summary>
/// <param name="pathBefore">原格式文件路径(绝对路劲)</param>
/// <param name="pathLater">转换后文件路径(绝对路劲)</param>
/// <returns></returns>
public string ConvertToMp3(string pathBefore, string pathLater)
{
string c = Util.BaseDirectory.TrimEnd('\\') + "\\Tools\\ffmpeg\\ffmpeg.exe -i " + pathBefore + " -f mp3 -acodec libmp3lame -y " + pathLater;
string str = RunCmd(c);
return str;
}
/// <summary>
/// 执行Cmd命令
/// </summary>
private string RunCmd(string c)
{
try
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo("cmd.exe");
info.RedirectStandardOutput = false;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
p.StandardInput.WriteLine(c);
p.StandardInput.AutoFlush = true;
System.Threading.Thread.Sleep();
p.StandardInput.WriteLine("exit");
p.Close();
p.WaitForExit();
string outStr = p.StandardOutput.ReadToEnd();
//p.Close(); return outStr;
}
catch (Exception ex)
{
return "error" + ex.Message;
}
}
#endregion
3.转换文件工具
预览 excel、word、txt、图片、pdf、html、音视频等文件(涉及到格式转换,用到ffmpeg、pdf2swf、wkhtmltopdf工具,iTextSharp类,Aspose(破解版)类、Microsoft.Office.Interop.Excel、Word类、swf文件预览插件FlexPaper)
C#文件网页预览: https://blog.csdn.net/lixiaoer757/article/details/80277617
net 预览文件 转换文件的更多相关文章
- mac如何用quick look预览多个文件或者图片
1.先选中要查看的多个文件,然后点击 空格键 2.按住 command+return 就可以同时预览多个文件了 如果想全屏预览,则在1中,按住 option+空格键 ,然后再进行2 ,就实现全屏预览了 ...
- ahk实现git图床自动预览以及转换markdown格式
ahk实现git图床自动预览以及转换markdown格式 软件地址 https://gitee.com/layty/pic/tree/master/app 软件功能: 检测剪切板,如果剪切板有非文本信 ...
- .net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览
转自源地址:http://www.cnblogs.com/GodIsBoy/p/4009252.html,有部分改动 使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pd ...
- (JavaScript)实现上传图片实时预览和(文件)大小判断
唉,为什么我一个做大数据和后端的要为前端耗尽心力啊??!! 昨天在做一个网页时遇到了一个问题,有一处需要插入图片,我原本的想法是获取到上传文件的URL,然后动态插入img标签,设置src为图片的URL ...
- vscode如何用浏览器预览运行html文件
1,打开vscode编辑器,点击编辑器主界面左上侧第五个小图标——‘扩展’按钮: 2,进入扩展搜索右拉框,在应用商店搜索框中输入“view in browser”会自动进行搜索 3,等待几秒钟时间,扩 ...
- 在网页中预览excel表格文件
项目需求在前端页面中实现预览excel表格的功能,上网了解之后大致总结为一下几种方法. 1.office文档转换为pdf,再转swf,然后通过网页加载flash进行预览 2.通过 xlsx.js,js ...
- Sublime下MarkDown插件实现编辑和实时预览并转换成HTML格式
最近在使用markdown做笔记,编辑器Sublime Text3用起来很轻巧,现在让他支持markdown的语法并且可以实时预览. 安装准备——安装Package Control Package C ...
- 前端实现图片上传预览并转换base64
前端实现文件的上传,就必须用到input标签,type属性为file. 在vue项目中通ref操作dom.input有一个属性accept,是必须要搭配type=file使用. multiple可以上 ...
- 使用NextCloud搭建私有网络云盘并支持Office文档在线预览编辑以及文件同步
转载自:https://www.bilibili.com/read/cv16835328?spm_id_from=333.999.0.0 0x00 前言简述 描述:由于个人家里的NAS以及公司团队对私 ...
随机推荐
- VSCODE 针对调试C语言时一闪而过解决办法
针对调试C语言时一闪而过解决办法 前提: 已经按照 C/C++ 已经安装 MINGW(并配置完成) 原因: 主要是因为tasks的配置没有写对 解决办法: tasks.json { // See h ...
- Dos命令 WIN10 WIFI命令
设置WIFI命令: netsh wlan set hostednetwork ssid=T key=123456798 mode=allow netsh wlan start hostednetwor ...
- php代码审计6审计xss漏洞
跨站脚本攻击(Cross Site Scripting)是指攻击者利用网站程序对用户输入过滤不足,输入可以显示在页面上对其他用户造成影响的html代码,从而盗取用户资料,利用用户身份进行某种动作或者对 ...
- Selenium3+python异常后截图(screenshot)
前言 在执行用例过程中由于是无人值守的,用例运行报错的时候,我们希望能对当前屏幕截图,留下证据. 在写用例的时候,最后一步是断言,可以把截图的动作放在断言这里,那么如何在断言失败后截图呢? 一.截图方 ...
- 常用跨平台IDE如何添加main函数的参数并正确执行
1. Eclipse-cdt如何添加main函数参数: 打开eclipse,新建工程.新建源文件,此处以C语言为例,写入代码如下: #include <stdio.h> //int arg ...
- LongAdder源码学习
原文链接:https://blog.csdn.net/u011392897/article/details/60480108 LongAdder是jdk8新增的用于并发环境的计数器,目的是为了在高并发 ...
- Python获取网页Html文本
Python爬虫基础 1.获取网页文本 通过urllib2包,根据url获取网页的html文本内容并返回 #coding:utf-8 import requests, json, time, re, ...
- WPF:CheckBox竖向的滑块效果
原文:WPF:CheckBox竖向的滑块效果 之前做了一个横向的滑块效果,<WPF:CheckBox滑块效果>,其实我觉得那个不好看,今天又做了一个竖向的玩. <Style Targ ...
- sock文件
无论是mysql,uwsgi还是nginx都会用到sock文件 首先它是由程序自动创建的,并不是我们自己手动.它的作用是用来通信.与之相对应的是tcp socket ,一般的程序会同时支持这两种方式, ...
- day--40 mysql-视图,触发器,存储过程,函数总结
视图,触发器,存储过程,函数总结 一:视图 01:介绍 视图是一个虚拟表(非真实存在),是跑到内存中的表,真实表是硬盘上的表,怎么就得到了虚拟表,就是你查询的结果,只不过之 前我们查询出来的虚拟表,从 ...