下載Aspose對應插件並添加引用
//文件名 string fileName; //文件類型 string fileType; //office文件路徑,形如 E://test.docx string allPath=HttpContext.Current.Server.MapPath("\\File\\")+fileName+"."+fileType; //保存路徑,形如 E://test.pdf string newPath=HttpContext.Current.Server.MapPath("\\File\\")+fileName+".pdf"; fileType = fileType.ToLower(); if (fileType.Contains("doc")) { //去除word文件的修改痕跡 Document doc = new Document(allPath); doc.AcceptAllRevisions(); //獲取所有修訂 doc.TrackRevisions = false; //不保留修訂記錄 doc.Save(newPath, Aspose.Words.SaveFormat.Pdf); } else if (fileType.Contains("xls")) { //如果表格大於A4寬度會出現截斷情況,插件自帶的一頁顯示方法沒了,采用讀取表格寬度進行縮放 Workbook document = new Workbook(allPath); Aspose.Cells.WorksheetCollection sheet = document.Worksheets; for (int i = 0; i < sheet.Count; i++) { Aspose.Cells.Worksheet ws = sheet[i]; Aspose.Cells.Cells cells = ws.Cells; int columnCount = cells.MaxColumn + 1; //獲取表頁的最大列數 double tableLength = 0; //表格總寬度 for (int col = 0; col < columnCount; col++) { tableLength += cells.GetColumnWidthPixel(col); } //24像素=0.635厘米 //A4紙寬度(21厘米)-左右邊距(1.78 * 2厘米,應該還有哪里有所減,因為就這樣計算出來還是不准確,所以我直接減5) / 0.635厘米 * 24像素 / 獲取到的表格總寬度 * 100 = 縮放比例 double prevent = Math.Floor((21 - 5) / 0.635 * 24 / tableLength * 100); if (prevent < 100) { ws.PageSetup.Zoom = (int)prevent; } //縮小還好,放大會有誤差,而且會失真,所以就不放大了 //else //{ // document.Save(newPath, Aspose.Cells.SaveFormat.Pdf); //} } PdfSaveOptions options = new PdfSaveOptions(); options.DefaultFont = "宋體"; document.Save(newPath, options); } else if (fileType.Contains("ppt")) { Presentation ppt = new Presentation(allPath); ppt.Save(newPath, Aspose.Slides.Export.SaveFormat.Pdf); }
