- A+
所属分类:.NET技术
在写完这三个需求之后 word转PDF,PDF添加水印,并控制显示的页数,JPG转PDF
新的需求接踵而来 将这三个功能合并 防灾H5页面上 边学习边记录,后面还会整理一些做微信深度开发时所用到的一些技术
下面看实际效果
针对目前的需求只实现了这些功能 如果运用到其他项目中扩展的话会继续更新
用到的引用
下面上代码
前端页面
@{ ViewBag.Title = "Home Page"; } <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script> <script src="~/Scripts/important/jquery.scrollLoading.min.js"></script> <script src="~/Scripts/important/fileUpload.min.js"></script> <div style="display:flex;"> <div id="pdfsrc" style="border:1px solid red;height:700px;width:1000px;margin-top:50px;"> <embed src="http://localhost:44344/pdfjs/web/viewer.html?file=http://localhost:44344/aaa/aca.pdf" width="100%" height="100%"></embed> </div> <div style="border:1px solid red;height:700px;width:1000px;margin-top:50px;margin-left:20px;"> <label>水印内容</label> <input type="text" id="mark" /><br /> <label>开始页</label> <input type="number" id="pageindex" /><br /> <label>可以看几页</label> <input type="number" id="pagesize" /><br /> <label>角度</label> <input type="number" id="jd" /><br /> <label>大小</label> <input type="number" id="dx" /><br /> <label>颜色</label> <select id="color"> <option value="Blue" selected="selected">蓝色</option> <option value="Orange">橙色</option> <option value="Olive">黄褐色</option> <option value="Navy">海军蓝</option> <option value="Moccasin">蛇皮色</option> <option value="MidnightBlue">深蓝</option> <option value="Lime">石灰色</option> <option value="Maroon">紫褐色</option> <option value="Magenta">桃红色</option> <option value="PapayaWhip">番木瓜色</option> <option value="SteelBlue">钢蓝色</option> <option value="White">白色</option> <option value="Yellow">黄色</option> <option value="Azure">蔚蓝色</option> <option value="Black">黑色</option> <option value="Gold">金色</option> <option value="Green">绿色</option> <option value="Gray">灰色</option> <option value="Ivory">象牙色</option> </select> <input type="button" value="添加水印" id="tjsy" class="search-btn ml5" style="width:65px"> <br /> <input type="text" /> <input type="file" style="display:none;" name="fileToUpload" onchange="fileSelected();" value="" id="openw" class="none" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword" /> <input type="button" value="Word转PDF" id="isoks-upload" class="search-btn ml5" style="width:105px"> <input type="hidden" id="urls" /> <input type="hidden" id="urlsT" /><br /> <input type="text" /> <input type="file" style="display:none;" name="fileToUpload" onchange="fileSelectedimage();" value="" id="openimage" class="none" accept="image/png,image/jpeg" /> <input type="button" value="图片转PDF" id="isoks_images" class="search-btn ml5" style="width:105px" /> </div> </div> <script> $(function () { isoks_upload(); isoks_images(); $("#tjsy").click(function () { var url = $("#urls").val(); var mark = $("#mark").val(); if (mark == "" || url == "") { alert("请上传文件或填写水印内容"); return false; } var pageIndex = $("#pageindex").val(); var pageSize = $("#pagesize").val(); var color = $("#color").val(); var jd = $("#jd").val(); var dx = $("#dx").val(); $.post("/Home/PDFAddMark", { url, mark, pageIndex, pageSize, color,jd,dx }, function (msg) { if (msg.State) { $("#pdfsrc").html(""); $("#pdfsrc").html(" <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>"); $("#urlsT").val(msg.Msg); } else { alert("失败"); return false; } }); }) }); /** * 一键上传 */ function fileSelected() { var file = $this[0].files[0]; if (file) { var fileSize = 0; if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; } uploadFile(file); } function uploadFile(file) { var pageindex = $("#pageindex").val(); var pagesize = $("#pagesize").val(); var fd = new FormData(); fd.append($this.attr('name'), file); file_uploadFileParam(fd, $this.attr('name'), "/Home/fileToUpload?pageIndex=" + pageindex + "&pageSize=" + pagesize, null, uploadComplete, uploadFailed, uploadCanceled) } function uploadComplete(evt) { var msg = evt.target.responseText; console.log(msg); msg = $.parseJSON(msg); if (msg.State) { $this.prev().val(msg.Msg); console.log(msg.Msg); $("#pdfsrc").html(""); $("#pdfsrc").html(" <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>"); $("#urls").val(msg.Msg); alert("成功"); //$this.prev().prev().attr("src", msg.Msg); } else { //$.alertboxsml(msg.Msg); //window.location.href = "/product/index"; alert("失败"); } } function uploadFailed(evt) { $.alertboxsml("上传失败!"); } function uploadCanceled(evt) { $.alertboxsml("上传中断!"); } //一键上传 function isoks_upload() { $("#isoks-upload").click(function () { $this = $("#openw"); $this.click(); }) } //一键上传 function isoks_images() { $("#isoks_images").click(function () { $this = $("#openimage"); $this.click(); }) } function fileSelectedimage() { var file = $this[0].files[0]; if (file) { var fileSize = 0; if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; } uploadFileimage(file); } function uploadFileimage(file) { var pageindex = $("#pageindex").val(); var pagesize = $("#pagesize").val(); var fd = new FormData(); fd.append($this.attr('name'), file); file_uploadFileParam(fd, $this.attr('name'), "/Home/ImageToPdf", null, uploadCompleteimg, uploadFailedimg, uploadCanceledimg) } function uploadCompleteimg(evt) { var msg = evt.target.responseText; console.log(msg); msg = $.parseJSON(msg); if (msg.State) { $this.prev().val(msg.Msg); console.log(msg.Msg); $("#pdfsrc").html(""); $("#pdfsrc").html(" <embed src='http://localhost:44344/pdfjs/web/viewer.html?file=" + msg.Msg + "' width='100%' height='100%'></embed>"); $("#urls").val(msg.Msg); alert("成功"); //$this.prev().prev().attr("src", msg.Msg); } else { //$.alertboxsml(msg.Msg); //window.location.href = "/product/index"; alert("失败"); } } function uploadFailedimg(evt) { $.alertboxsml("上传失败!"); } function uploadCanceledimg(evt) { $.alertboxsml("上传中断!"); } </script>
Controller里面的代码
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using KSir; namespace PDFTest.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } /// <summary> /// 将word转为pdf /// </summary> /// <param name="pageIndex">开始页</param> /// <param name="pageSize">可以看几页</param> /// <param name="fileToUpload">word文件</param> /// <returns></returns> public ActionResult fileToUpload(string pageIndex, string pageSize, HttpPostedFileBase fileToUpload) { try { if (fileToUpload == null) return Json_IsoksError("系统错误!"); var t = KsirUpload.Isoks_UploadFile(fileToUpload, "PDF"); if (string.IsNullOrWhiteSpace(t)) { return Json_IsoksError("哎呀,出错了"); } var suffix = Path.GetExtension(fileToUpload.FileName); var pd = PDFInfo.WordToPDFWithOffice(t, t.Replace(suffix, ".pdf"), pageIndex, pageSize); //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString(); var url = ConfigurationManager.AppSettings["ImgPath"]; string path = url + "/UploadFiles/AnotherFile/PDF/" + Path.GetFileName(t).Replace(suffix, ".pdf"); return Json_IsoksSuccess(path); } catch (Exception ex) { return Json_IsoksError("哎呀,出错了"); } } /// <summary> /// 给PDF添加水印 /// </summary> /// <param name="url">PDF本地地址</param> /// <param name="mark">水印内容</param> /// <param name="pageIndex">开始页</param> /// <param name="pageSize">可以看几页</param> /// <param name="color">水印颜色</param> /// <param name="jd">水印角度</param> /// <param name="dx">水印大小</param> /// <returns></returns> public ActionResult PDFAddMark(string url, string mark, string pageIndex, string pageSize, string color, float jd = -45, float dx = 24) { string str = System.AppDomain.CurrentDomain.BaseDirectory + url.Replace(ConfigurationManager.AppSettings["ImgPath"], ""); //string strPhycicsPath = Server.MapPath(url); var suffix = Path.GetFileName(str).Replace(".pdf", "") + "1.pdf"; var marks = KSir.PDFInfo.PDFAddMark(str, str.Replace(Path.GetFileName(str), suffix), mark, pageIndex, pageSize, color, jd,dx); if (marks) { return Json_IsoksSuccess(url.Replace(Path.GetFileName(str), suffix)); } else { return Json_IsoksError("失败"); } } /// <summary> /// 图片转PDF /// </summary> /// <param name="fileToUpload"></param> /// <returns></returns> public ActionResult ImageToPdf(HttpPostedFileBase fileToUpload) { try { if (fileToUpload == null) return Json_IsoksError("系统错误!"); var t = KsirUpload.Isoks_UploadFile(fileToUpload, "PDF"); if (string.IsNullOrWhiteSpace(t)) { return Json_IsoksError("哎呀,出错了"); } var suffix = Path.GetExtension(fileToUpload.FileName); var pd = PDFInfo.ConvertJPG2PDF(t, t.Replace(suffix, ".pdf")); //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString(); var url = ConfigurationManager.AppSettings["ImgPath"]; string path = url + "/UploadFiles/AnotherFile/PDF/" + Path.GetFileName(t).Replace(suffix, ".pdf"); return Json_IsoksSuccess(path); } catch (Exception ex) { return Json_IsoksError("哎呀,出错了"); } } public bool IsoksIsNullOrWhiteSpace(params string[] value) { for (int i = 0; i < value.Length; i++) { if (string.IsNullOrWhiteSpace(value[i])) return false; } return true; } #region isoks-json /// <summary> /// Json-Success /// Author: /// Return:[{State:true,Msg=Msg}] /// </summary> /// <param name="c"></param> /// <param name="Msg"></param> /// <returns></returns> public ActionResult Json_IsoksSuccess(object Msg, JsonRequestBehavior GetOrPost = JsonRequestBehavior.DenyGet) { return Json(new { State = true, Msg = Msg }, GetOrPost); } /// <summary> /// Json-Error /// Author: /// Return:[{State:true,Msg=Msg}] /// </summary> /// <param name="c"></param> /// <param name="Msg"></param> /// <returns></returns> public ActionResult Json_IsoksError(object Msg, JsonRequestBehavior GetOrPost = JsonRequestBehavior.DenyGet) { return Json(new { State = false, Msg = Msg }, GetOrPost); } public static class Isok { /// <summary> /// json-get /// </summary> public const JsonRequestBehavior Get = JsonRequestBehavior.AllowGet; } #endregion } }
KsirUpload.cs 代码
using System; using System.Configuration; using System.IO; using System.Threading.Tasks; using System.Web; namespace KSir { public static class KsirUpload { public static string Isoks_UploadImg(HttpPostedFileBase fileToUpload, string pathUri) { try { if (fileToUpload == null) return string.Empty; //获取文件后缀 var suffix = Path.GetExtension(fileToUpload.FileName); if (string.IsNullOrWhiteSpace(suffix)) return string.Empty; if (suffix.ToLower() != ".jpg" && suffix.ToLower() != ".png" && suffix.ToLower() != ".gif" && suffix.ToLower() != ".bmp" && suffix.ToLower() != ".mp4" && suffix.ToLower() != ".avi") return string.Empty; var stream = fileToUpload.InputStream; Random r = new Random(); var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9); string directory = HttpContext.Current.Server.MapPath("/UploadFiles/" + pathUri + "/"); //判断目录是否存在 if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString(); string path = url + "/UploadFiles/" + pathUri + "/" + fileName + suffix; var _path = directory + fileName + suffix; fileToUpload.SaveAs(_path); return path; } catch (Exception ex) { return string.Empty; } } public static string Isoks_UploadFile(HttpPostedFileBase fileToUpload, string pathUri) { try { if (fileToUpload == null) return string.Empty; //获取文件后缀 var suffix = Path.GetExtension(fileToUpload.FileName); if (string.IsNullOrWhiteSpace(suffix)) return string.Empty; var stream = fileToUpload.InputStream; Random r = new Random(); var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9); string directory = HttpContext.Current.Server.MapPath("/UploadFiles/AnotherFile/" + pathUri + "/"); //判断目录是否存在 if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string url = ConfigurationManager.AppSettings["ImgPath"]; //var url = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ImgPath"].ToString(); string path = url + "/UploadFiles/AnotherFile/" + pathUri + "/" + fileName + suffix; var _path = directory + fileName + suffix; fileToUpload.SaveAs(_path); return _path; } catch (Exception ex) { return string.Empty; } } public static string Isoks_UploadExcel(HttpPostedFileBase fileToUpload, string pathUri) { try { if (fileToUpload == null) return string.Empty; //获取文件后缀 var suffix = Path.GetExtension(fileToUpload.FileName); if (string.IsNullOrWhiteSpace(suffix)) return string.Empty; var stream = fileToUpload.InputStream; Random r = new Random(); var fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + r.Next(9) + r.Next(9) + r.Next(9) + r.Next(9); string directory = HttpContext.Current.Server.MapPath("/UploadFiles/AnotherFile/" + pathUri + "/"); //判断目录是否存在 if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string path = "/UploadFiles/AnotherFile/" + pathUri + "/" + fileName + suffix; var _path = directory + fileName + suffix; fileToUpload.SaveAs(_path); return _path; } catch (Exception ex) { return string.Empty; } } public static byte[] StreamToBytes(Stream stream) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Seek(0, SeekOrigin.Begin); return buffer; } } }
PDFInfo.cs 代码
using iTextSharp.text.pdf; using Microsoft.Office.Interop.Word; using Spire.Pdf; using Spire.Pdf.Graphics; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using System.Web; namespace KSir { public static class PDFInfo { /// <summary> /// 将word转成PDF office /// </summary> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> /// <returns></returns> public static bool WordToPDFWithOffice(string sourcePath, string targetPath, string fromPage, string toPage) { bool result = false; Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Document document = null; try { application.Visible = false; document = application.Documents.Open(sourcePath); /* 参数参考 https://docs.microsoft.com/zh-cn/office/vba/api/visio.document.exportasfixedformat */ int pageindex = 1; object Nothing = Missing.Value; if (!string.IsNullOrEmpty(fromPage)) { pageindex = int.Parse(fromPage); } int pagesize = document.ComputeStatistics(WdStatistic.wdStatisticPages, ref Nothing); if (!string.IsNullOrEmpty(toPage)) { pagesize = int.Parse(toPage); } document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportFromTo, pageindex, pagesize); result = true; } catch (Exception e) { //Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return result; } /// <summary> /// 给PDF文件添加水印 /// </summary> /// <param name="pdfPath">需要添加水印的pdf文件路径</param> /// <param name="targetPath">添加成功之后的文件路径和文件名</param> /// <param name="marks">水印内容</param> /// <param name="fromPage">可以从第几页开始看</param> /// <param name="toPage">可以看多少页</param> /// <returns></returns> public static bool PDFAddMark(string pdfPath, string targetPath, string marks, string pageindex, string pagesize, string color, float jd = -45, float dx = 24) { bool result = false; try { //创建一个新的PDF实例。然后导入PDF文件。 Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument(); pdf.LoadFromFile(pdfPath); //这里是因为Spire的版本问题 第一页会被添加水印 PdfPageBase pb = pdf.Pages.Add(); //新增一页 pdf.Pages.Remove(pb); //去除第一页水印 var a = pdf.Pages.Count; int fromPage = 1; if (!string.IsNullOrEmpty(pageindex)) { fromPage = int.Parse(pageindex); } int toPage = a; if (!string.IsNullOrEmpty(pagesize)) { toPage = int.Parse(pagesize); } if (fromPage > a) { fromPage = 1; } if (fromPage > 1 && toPage < a) { for (int i = 0; i < (a - toPage); i++) { pdf.Pages.Remove(pdf.Pages[pdf.Pages.Count - 1]); //去掉后面的页数 } for (int i = 1; i < fromPage; i++) { pdf.Pages.Remove(pdf.Pages[0]); //去掉前面的页数 } } else if (fromPage > 1) { for (int i = 1; i < fromPage; i++) { pdf.Pages.Remove(pdf.Pages[0]); //去掉前面的页数 } } else if (toPage < a) { for (int i = 0; i < (a - toPage); i++) { pdf.Pages.Remove(pdf.Pages[pdf.Pages.Count - 1]); //去掉后面的页数 } } var col = PdfBrushes.Blue; if (color == "Orange") { col = PdfBrushes.Orange; } else if (color == "Olive") { col = PdfBrushes.Olive; } else if (color == "Navy") { col = PdfBrushes.Navy; } else if (color == "Moccasin") { col = PdfBrushes.Moccasin; } else if (color == "MidnightBlue") { col = PdfBrushes.MidnightBlue; } else if (color == "Lime") { col = PdfBrushes.Lime; } else if (color == "Maroon") { col = PdfBrushes.Maroon; } else if (color == "Magenta") { col = PdfBrushes.Magenta; } else if (color == "PapayaWhip") { col = PdfBrushes.PapayaWhip; } else if (color == "SteelBlue") { col = PdfBrushes.SteelBlue; } else if (color == "White") { col = PdfBrushes.White; } else if (color == "Yellow") { col = PdfBrushes.Yellow; } else if (color == "Azure") { col = PdfBrushes.Azure; } else if (color == "Black") { col = PdfBrushes.Black; } else if (color == "Gold") { col = PdfBrushes.Gold; } else if (color == "Green") { col = PdfBrushes.Green; } else if (color == "Gray") { col = PdfBrushes.Gray; } else if (color == "Ivory") { col = PdfBrushes.Ivory; } else { col = PdfBrushes.Blue; } PdfPageBase page = null; if (pdf.Pages.Count > 0) { for (int i = 0; i < pdf.Pages.Count; i++) { page = pdf.Pages[i]; PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3)); brush.Graphics.SetTransparency(0.3f);//设置透明度 brush.Graphics.Save(); brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);//设置平移变换 brush.Graphics.RotateTransform(jd);//设置角度 brush.Graphics.DrawString(marks, new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, dx), col, 0, 0, new PdfStringFormat(PdfTextAlignment.Center)); brush.Graphics.Restore(); brush.Graphics.SetTransparency(1);//设置透明度 page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize)); } pdf.SaveToFile(targetPath); return true; } return result; } catch (Exception ex) { return false; } } #region 图片转PDF /// <summary> /// 图片转PDF /// </summary> /// <param name="jpgfile">图片本地地址</param> /// <param name="pdf">生成的文件路径和文件名</param> /// <returns></returns> public static bool ConvertJPG2PDF(string jpgfile, string pdf) { var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) { try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); } catch (Exception ex) { } document.Open(); using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } document.Close(); } return true; } /// <summary> /// 图片转pdf /// </summary> /// <param name="jpgfile">要转换的图片的路径,不需要加后缀和标识的数字</param> /// <param name="pdfoutputpath">转成后的文件地址和文件名</param>] /// <param name="count">图片的数量</param> public static void ImageToPDF(string jpgfile, string pdfoutputpath, int count) { var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (var stream = new FileStream(pdfoutputpath, FileMode.Create, FileAccess.Write, FileShare.None)) { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); document.Open(); for (int i = 1; i <= count; i++) { using (var imageStream = new FileStream(jpgfile + i + ".jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Element.ALIGN_MIDDLE; document.NewPage(); document.Add(image); } } document.Close(); } } #endregion } }
学习记录贴 有朋友发现任何不对的地方欢迎指出,有大佬有更简洁方便的方法也希望可以告诉我 欢迎评论