iTextSharp 使用 以Excel 建立 PDF
這是一個從2000年左右就開始在使用的函式庫,用於畫一個PDF出來。
現代應該都是用Word套版另存新檔變成PDF 用的應該是匯出PDF
但是假如你家的Office是低於等於2007版本(有一個版本之後才能直接另存新檔成PDF)
那你就得 手刻 大概
public ActionResult PDF(HttpPostedFileBase file)
{
//建立文件 用於建立PDF
Document doc = new Document();
//從直行變橫
doc.SetPageSize(doc.PageSize.Rotate());
//建立MemoryStream
MemoryStream ms = new MemoryStream();
//取得相對 根路徑 用於儲存xls檔案進入目標位置用於讀取
//這邊讀取的是Excel
string pathXls = Server.MapPath("~/xls");
try
{
//若path不存在,建立
#region PDF建立
if (!System.IO.Directory.Exists(pathXls))
System.IO.Directory.CreateDirectory(pathXls);
#endregion
//建立xls檔案路徑
string xlsfilepath = "";
//若有xlsfile傳入
if (file != null)
{
//取得傳入的file Name
string fileName = Path.GetFileName(file.FileName);
//建立filepath用於儲存
xlsfilepath = Path.Combine(pathXls, fileName);
file.SaveAs(xlsfilepath);
}
else
{
ViewBag.Message = "無上傳檔案";
return View("Index");
}
//PDF建立
PdfWriter pdfw = PdfWriter.GetInstance(doc, ms);
//建立字體路徑 每台可能不一樣 可能沒這個字體 因此存進fonts中讀取
string PDFPath = Server.MapPath("~/fonts");
//建立PDFS字型
BaseFont bfchinese = BaseFont.CreateFont(PDFPath + @"\kaiu.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font chFont = new Font(bfchinese, 12);
//建立Excel檔案
//判斷後段是否為xls 或者 xlsx
IWorkbook workbook;
using (FileStream fs = new FileStream(xlsfilepath, FileMode.Open, FileAccess.Read))
{
//切FileName
string[] spiltFileName = file.FileName.Split('.');
//抓最後一個spilt位置 如 2022.01.26temp.xls 因此抓最後一個
//區分xls 和 xlsx
if (spiltFileName[spiltFileName.Length - 1] == "xls")
workbook = new HSSFWorkbook(fs);
else workbook = new XSSFWorkbook(fs);
}
//判斷Sheet和Row
int SheetCount = 0;
int RowCount = 1;
try
{
//開啟doc文件
doc.Open();
//走訪每一個Sheet
while (SheetCount < workbook.NumberOfSheets)
{
//取得目標Sheet
ISheet Sheet = workbook.GetSheetAt(SheetCount);
//取目標SheetRowCount走訪用
int iRow = Sheet.LastRowNum;
//走訪Sheet 建立PDF文件
while (RowCount < iRow)
{
//取得Row
IRow row = Sheet.GetRow(RowCount);
//排版用 0 靠左 1靠中 2靠右
//建立段落,縮排 內容 字體
Paragraph p = new Paragraph(15f, @"Test:", chFont);
//對齊 0 1 2 左 中 右
p.Alignment = 0;
doc.Add(p);
//建立PDF Table PDFTable格式 1格
//假如在裡面建立float陣列則可以建立一個多格子一行的Table
PdfPTable table = new PdfPTable(1);
//table = new PdfPTable(new float[] { 3, 6, 10, 10 });
//設定PDF Table寬度
table.TotalWidth = 800f;
//PDF Table寬度鎖定,不會因為字數過少縮減
table.LockedWidth = true;
//建立Cell存入Table中
PdfPCell Test = new PdfPCell();
Test = new PdfPCell(new Phrase("測試", chFont));
//設定Cell最小高度及字體置中
Test .MinimumHeight = 30;
Test .VerticalAlignment = Element.ALIGN_MIDDLE;
//寫入Table中
table.AddCell(Test );
//Table寫入doc中
doc.Add(table);
//建立img server path 直接抓相對根目錄
string imgPath = Server.MapPath("~/img");
//建立img圖片檔案 設定圖片位置及圖片大小
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri(imgPath + "\\sign.jpg"));
//為了刪除框線,塞入Cell
c = new PdfPCell(img);
//刪除BORDER框線
c.DisableBorderSide(Rectangle.BOTTOM_BORDER);
c.DisableBorderSide(Rectangle.TOP_BORDER);
c.DisableBorderSide(Rectangle.LEFT_BORDER);
c.DisableBorderSide(Rectangle.RIGHT_BORDER);
c.FixedHeight = 40f;
//下面這條是可以把兩列合併成一列
//c.Colspan = 2;
//寫入Table中
table.AddCell(c);
//Add Table
doc.Add(table);
//開新分頁 用於排版
doc.NewPage();
}
SheetCount++;
}
//關閉文件輸入,建立文件
doc.Close();
//取名稱不取檔案類別
string fileName = file.FileName.Replace(".xlsx", "");
fileName = file.FileName.Replace(".xls", "");
//清空Response
Response.Clear();
//建立標頭及type
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".pdf");
Response.ContentType = "application/octet-stream";
//寫入Response
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
//清空並歸還空間
ms.Flush();
ms.Dispose();
ms.Close();
Response.OutputStream.Flush();
Response.OutputStream.Close();
Response.Flush();
return View("Query");
}
catch (Exception e)
{
ViewBag.Message = file.FileName + e.Message;
}
finally
{
workbook.Close();
System.IO.File.Delete(xlsfilepath);
}
}
//IO錯誤
catch (IOException e)
{
ViewBag.Message = e.Message;
}
//其餘錯誤
catch (Exception e)
{
ViewBag.Message = e.Message;
}
//成功完成整趟寫入
if (ViewBag.Message == null)
{
ViewBag.Message = "成功寫入";
}
return View("Query");
}
留言
張貼留言