C#+Aspose轉office文檔為PDF


下載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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM