C# 文档操作

        
        /// <summary>
        /// Word文件转pdf格式后返回文件流预览
        /// </summary>
        [AllowAnonymous]
        [HttpGet("/sysFileInfo/previewWordFile")]
        public async Task<IActionResult> PreviewWordFile([FromQuery] QueryFileInfoInput input)
        {
            var file = await GetFileInfo(input);
            string fileName = file.Id.ToString(),
                   wordPath = App.WebHostEnvironment.WebRootPath + "/" + file.FilePath + "/",
                   previewPath = wordPath + "PreviewPDF/",
                   pdfPath = previewPath + fileName + ".pdf";
            WordToPdf(previewPath, pdfPath, wordPath + fileName + "." + file.FileSuffix);
            if (!File.Exists(pdfPath)) { return null; }
            return new FileStreamResult(new FileStream(pdfPath, FileMode.Open), "application/pdf");
        }

        /// <summary>
        /// Excel文件转Html格式后返回文件流预览
        /// </summary>
        [AllowAnonymous]
        [HttpGet("/sysFileInfo/previewExcelFile")]
        public async Task<IActionResult> PreviewExcelFile([FromQuery] QueryFileInfoInput input)
        {
            var file = await GetFileInfo(input);
            file.FileSuffix = "." + file.FileSuffix;
            string fileName = file.Id.ToString(),
                   excelPath = App.WebHostEnvironment.WebRootPath + "/" + file.FilePath + "/",
                   previewPath = excelPath + "PreviewExcel/",
                   htmlPath = previewPath + fileName + ".html";
            if (!File.Exists(htmlPath))
            {
                ExcelToHtml(previewPath, htmlPath, excelPath + fileName + file.FileSuffix, file.FileSuffix);
            }
            if (!File.Exists(htmlPath)) { return null; }
            return new FileStreamResult(new FileStream(htmlPath, FileMode.Open), "text/html");
        }

        private string GetPreviewContentType(string fileName)
        {
            switch (fileName.Split('.').LastOrDefault().ToUpper())
            {
                case "TXT":
                    return "text/plain;charset=utf-8";
                case "SQL":
                    return "text/html";
                case "PDF":
                    return "application/pdf";
                case "HTML":
                    return "text/html";
                case "PNG":
                    return "image/png";
                case "JPG":
                    return "image/jpg";
                case "JPEG":
                    return "image/jpeg";
                case "XML":
                    return "text/xml";
                case "O2O":
                    return "text/plain";
                default:
                    return "application/octet-stream";
            }
        }

        /// <summary>
        /// Word文档转Pdf
        /// </summary>
        /// <param name="previewPath">Pdf文件保存路径</param>
        /// <param name="pdfPath">Pdf文件路径</param>
        /// <param name="wordPath">Word文件路径</param>
        public void WordToPdf(string previewPath, string pdfPath, string wordPath)
        {
            previewPath = previewPath.Replace("/", "\\");
            if (!File.Exists(wordPath)) { return; }
            if (!Directory.Exists(previewPath)) { Directory.CreateDirectory(previewPath); }
            try
            {
                if (!File.Exists(pdfPath))
                {
                    Aspose.Words.Document doc = new Aspose.Words.Document(wordPath);
                    doc.Save(pdfPath);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }

        /// <summary>
        /// Excel文档转Html
        /// </summary>
        /// <param name="previewPath">预览html文件的存放完整路径</param>
        /// <param name="htmlPath">html文件的存放路径</param>
        /// <param name="excelPath">excel文件的存放路径</param>
        /// <param name="fileExt">文件后缀名 .xlsx or .xls</param>
        public void ExcelToHtml(string previewPath, string htmlPath, string excelPath, string fileExt)
        {
            previewPath = previewPath.Replace("/", "\\");
            excelPath = excelPath.Replace("/", "\\");
            if (!File.Exists(excelPath)) { return; }
            if (!Directory.Exists(previewPath)) { Directory.CreateDirectory(previewPath); }
            try
            {
                if (!System.IO.File.Exists(htmlPath))
                {
                    NPOI.SS.UserModel.IWorkbook workbook;

                    string strHtml = "<html><head><style>.tabs{position:relative;min-height:200px;clear:both;margin:25px 0;}.tab{float:left}tr{height:20px;}.tab label{background:#eee;padding:10px;border:1px solid #ccc;margin-left:-1px;position:relative;left:1px;}.tab [type=radio]{display:none;}.content{position:absolute;width:98%;height:800px;overflow:auto;top:28px;left:0;background:white;right:0;bottom:0;padding:20px;border:1px solid #ccc;}[type=radio]:checked ~ label{background:white;border-bottom:1px solid white;z-index:2;}[type=radio]:checked ~ label ~ .content{z-index:1;}</style><meta http-equiv=\"Content-Type\" content =\"text/html; charset=UTF-8\" /></head><body><div class=\"tabs\" > ";
                    try
                    {
                        System.IO.FileStream stream = System.IO.File.OpenWrite(excelPath);
                        stream.Close();
                    }
                    catch
                    {
                        return;
                    }
                    using (FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
                    {
                        if (fileExt == ".xlsx")
                        {
                            workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fs);
                            if (workbook != null)
                            {
                                int numberOfSheets = workbook.NumberOfSheets;
                                for (int i = 0; i < numberOfSheets; i++)
                                {
                                    int index = i + 1;
                                    string checkedStr = index == 1 ? "checked" : "";
                                    strHtml += "<div class=\"tab\" ><input type=\"radio\" id =\"tab-" + index + "\" name =\"tab-group-1\" " + checkedStr + ">";
                                    strHtml += "<label for=\"tab-" + index + "\">" + workbook.GetSheetName(i) + "</label>";
                                    strHtml += "<div class=\"content\" > <table class=\"t1\" > ";
                                    string trHtml = string.Empty, tdHtml = string.Empty;
                                    foreach (NPOI.XSSF.UserModel.XSSFRow sheet in workbook.GetSheetAt(i))
                                    {
                                        tdHtml = string.Empty;
                                        int RowNum = sheet.RowNum;
                                        List<NPOI.SS.UserModel.ICell> cellsList = sheet.Cells;
                                        foreach (NPOI.SS.UserModel.ICell cell in cellsList)
                                        {
                                            string values = GetCellValue(cell);
                                            if (string.IsNullOrEmpty(values))
                                            {
                                                tdHtml += "<td></td>";
                                            }
                                            else
                                            {
                                                tdHtml += "<td>" + values + "</td>";
                                            }
                                        }
                                        if (string.IsNullOrEmpty(tdHtml))
                                        {
                                            trHtml += "<tr><td> &nbsp;</td></tr>";
                                        }
                                        else
                                        {
                                            trHtml += "<tr>" + tdHtml + "</tr>";
                                        }
                                    }

                                    if (string.IsNullOrEmpty(trHtml))
                                    {
                                        strHtml += "<tr><td>&nbsp;</td></tr>";
                                    }
                                    else
                                    {
                                        strHtml += trHtml;
                                    }
                                    strHtml += "</table></div></div>";
                                }
                            }
                        }
                        else if (fileExt == ".xls")
                        {
                            workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
                            if (workbook != null)
                            {
                                int numberOfSheets = workbook.NumberOfSheets;
                                for (int i = 0; i < numberOfSheets; i++)
                                {
                                    int index = i + 1;
                                    string checkedStr = index == 1 ? "checked" : "";
                                    strHtml += "<div class=\"tab\" ><input type=\"radio\" id =\"tab-" + index + "\" name =\"tab-group-1\" " + checkedStr + ">";
                                    strHtml += "<label for=\"tab-" + index + "\">" + workbook.GetSheetName(i) + "</label>";
                                    strHtml += "<div class=\"content\" > <table class=\"t1\" > ";
                                    string trHtml = string.Empty, tdHtml = string.Empty;
                                    foreach (NPOI.HSSF.UserModel.HSSFRow sheet in workbook.GetSheetAt(i))
                                    {
                                        tdHtml = string.Empty;
                                        int RowNum = sheet.RowNum;
                                        List<NPOI.SS.UserModel.ICell> cellsList = sheet.Cells;
                                        foreach (NPOI.SS.UserModel.ICell cell in cellsList)
                                        {
                                            string values = GetCellValue(cell);
                                            if (string.IsNullOrEmpty(values))
                                            {
                                                tdHtml += "<td></td>";
                                            }
                                            else
                                            {
                                                tdHtml += "<td>" + values + "</td>";
                                            }
                                        }
                                        if (string.IsNullOrEmpty(tdHtml))
                                        {
                                            trHtml += "<tr><td> &nbsp;</td></tr>";
                                        }
                                        else
                                        {
                                            trHtml += "<tr>" + tdHtml + "</tr>";
                                        }
                                    }

                                    if (string.IsNullOrEmpty(trHtml))
                                    {
                                        strHtml += "<tr><td>&nbsp;</td></tr>";
                                    }
                                    else
                                    {
                                        strHtml += trHtml;
                                    }
                                    strHtml += "</table></div></div>";
                                }
                            }
                        }
                        else
                        {
                            workbook = null;
                        }
                        if (workbook == null)
                        {
                            return;
                        }
                    }
                    strHtml += "</div></body></html>";

                    StreamWriter sw = new StreamWriter(htmlPath, false, Encoding.UTF8);
                    sw.Write(strHtml);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
        }

        public string GetCellValue(NPOI.SS.UserModel.ICell cell)
        {
            switch (cell.CellType)
            {
                case NPOI.SS.UserModel.CellType.Blank:
                    return string.Empty;
                case NPOI.SS.UserModel.CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case NPOI.SS.UserModel.CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case NPOI.SS.UserModel.CellType.Numeric: //数字类型
                    if (NPOI.HSSF.UserModel.HSSFDateUtil.IsCellDateFormatted(cell))//日期类型
                    {
                        return cell.DateCellValue.ToString();
                    }
                    else //其它数字
                    {
                        return cell.NumericCellValue.ToString();
                    }
                case NPOI.SS.UserModel.CellType.Unknown: //无法识别类型
                default: //默认类型
                    return cell.ToString();//
                case NPOI.SS.UserModel.CellType.String: //string 类型
                    return cell.StringCellValue;
                case NPOI.SS.UserModel.CellType.Formula: //带公式类型
                    try
                    {
                        NPOI.HSSF.UserModel.HSSFFormulaEvaluator e = new NPOI.HSSF.UserModel.HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }

使用到的相关dll:

链接:https://pan.baidu.com/s/1K7oPdqLJ92Lt_DE7gRUBwA 
提取码:jxwn

2.PDF转图片

        public static List<string> PdfImageToSave(string filePath)
        {
            List<string> result = new List<string>();
            try
            {
                string dir = App.WebHostEnvironment.WebRootPath + "/";
                string relateFilePath = dir + $"File/Temp/";
                if (!Directory.Exists(relateFilePath)) { Directory.CreateDirectory(relateFilePath); }

                var pdfPath = dir + filePath;
                pdfPath = pdfPath.Contains("\\") ? pdfPath.Replace("\\", "/") : pdfPath;
                string FileName = pdfPath.Split('/').LastOrDefault();
                if (!File.Exists(pdfPath)) { return result; }

                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfPath);

                for (int PageIndex = 1; PageIndex <= pdfDocument.Pages.Count; PageIndex++)
                {
                    string filePathOutPut = string.Empty;

                    if (pdfDocument.Pages.Count > 1)
                    {
                        filePathOutPut = FileName.Replace(Path.GetExtension(FileName), "") + "_" + PageIndex.ToString() + ".jpg";
                    }
                    else
                    {
                        filePathOutPut = FileName.Replace(Path.GetExtension(FileName), "") + ".jpg";
                    }
                    FileStream imageStream = new FileStream(relateFilePath + filePathOutPut, FileMode.Create);

                    try
                    {
                        Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(100); //质量(0-100)
                        Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution);
                        jpegDevice.Process(pdfDocument.Pages[PageIndex], imageStream);
                        imageStream.Close();

                        string base64 = string.Empty;
                        using (var fileStream = new FileStream(relateFilePath + filePathOutPut, FileMode.Open, FileAccess.Read))
                        {
                            fileStream.Seek(0, SeekOrigin.Begin);
                            var buffer = new byte[fileStream.Length];
                            fileStream.Read(buffer, 0, Convert.ToInt32(fileStream.Length));
                            base64 = Convert.ToBase64String(buffer);
                        }

                        string res = UploadFile(base64, filePathOutPut);

                        if (!String.IsNullOrEmpty(res))
                        {
                            result.Add(res.Replace("\\", "/"));
                        }
                    }
                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                        imageStream.Close();
                    }
                    finally
                    {
                        if (File.Exists(relateFilePath + filePathOutPut))
                        {
                            File.Delete(relateFilePath + filePathOutPut);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="base64">文件base64</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static string UploadFile(string base64, string fileName, string savePath = "")
        {
            string filePath = string.Empty;
            try
            {
                savePath = string.IsNullOrEmpty(savePath) ? $"File/UploadFile/{DateTime.Now.ToString("yyyy-MM-dd")}/" : savePath;
                string dir = App.WebHostEnvironment.WebRootPath + "/";
                filePath = savePath + fileName;
                savePath = dir + savePath;
                if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); }
                byte[] bytes = Convert.FromBase64String(base64);
                // 写入文件到指定位置
                using (FileStream fs = new FileStream(savePath + fileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            return filePath.Contains("\\") ? filePath.Replace("\\", "/") : filePath;
        }

3.图片集合转PDF文件

        public string ImageToPDF(List<string> imageNameList, string sign = "")
        {
            string pdfFilePath = string.Empty;
            try
            {
                string fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".pdf";
                string dir = App.WebHostEnvironment.WebRootPath;
                string filePath = $"UploadFile/{DateTime.Now.ToString("yyyy-MM-dd")}/";
                pdfFilePath = filePath + fileName;
                filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, filePath);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                using (Spire.Doc.Document document = new Spire.Doc.Document())
                {
                    Spire.Doc.Section section = document.AddSection();
                    foreach (string item in imageNameList)
                    {
                        System.Drawing.Image image = null;
                        if (item.IndexOf("http") >= 0)
                        {
                            // 设置参数
                            var request = WebRequest.Create(item) as HttpWebRequest;
                            //发送请求并获取相应回应数据
                            var response = request.GetResponse() as HttpWebResponse;
                            //直到request.GetResponse()程序才开始向目标网页发送Post请求
                            var responseStream = response.GetResponseStream();
                            image = System.Drawing.Image.FromStream(responseStream);
                        }
                        else if (File.Exists(dir + "/" + item))
                        {
                            image = System.Drawing.Image.FromFile(dir + "/" + item);
                        }
                        else
                        {
                            return "";
                        }
                        Spire.Doc.Documents.Paragraph para = section.AddParagraph();
                        Spire.Doc.Fields.DocPicture picture = para.AppendPicture(image);
                        if (image.Width > 350)
                        {
                            decimal p = image.Width / 350;
                            picture.Width = Convert.ToInt32(image.Width / p);
                            picture.Height = Convert.ToInt32(image.Height / p);
                        }
                        else
                        {
                            picture.Width = image.Width;
                            picture.Height = image.Height;
                        }
                    }

                    if (!string.IsNullOrEmpty(sign))
                    {
                        Spire.Doc.Documents.Paragraph para = section.AddParagraph();
                        Spire.Doc.Fields.TextRange textRange1 = para.AppendText(sign);
                        textRange1.CharacterFormat.TextColor = System.Drawing.Color.White;
                        textRange1.CharacterFormat.FontSize = 15;
                        textRange1.CharacterFormat.FontNameFarEast = "宋体";
                        textRange1.CharacterFormat.UnderlineStyle = Spire.Doc.Documents.UnderlineStyle.Dash;
                    }

                    document.SaveToFile(filePath + fileName, Spire.Doc.FileFormat.PDF);
                    document.Close();
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                return "";
            }
            return pdfFilePath;
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值