前段時間公司的產品,要做一個新功能,簽章(就是把需要的資料整理成PDF很標準的檔案,然後在蓋上我們在伺服器上面的章)
然後我就在百度上找了找,發現搞PDF的類庫很少,要麼就要錢,要麼就有水印,破解版的沒找到。
先講一講我是怎麼生成PDF的
1、生成PDF
這裡用到了 Spire.Pdf 這個類庫可以在NuGet裡面搜尋到,上面帶個小紅標的就是免費版本。
當然也可以去他們的官網,上面還有文件(https://www.e-iceblue.cn/Introduce/Spire-PDF-NET.html)。
程式碼(這是我自己寫的一個測試的表格)
public static void abc() { //建立PDF文件 Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument(); //新增一頁 PdfPageBase page = doc.Pages.Add(); //設定字型 PdfTrueTypeFont font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 20f), true); PdfTrueTypeFont font1 = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 11f), true); //建立一個PdfGrid物件 PdfGrid grid = new PdfGrid(); //這一段的內容是在表格只玩顯示一些資料 根據座標定位 第一個是內容,第二個是字型,第三個是顏色,第四第五是座標 page.Canvas.DrawString("XXXXXXXX管理中心回單", font, new PdfSolidBrush(System.Drawing.Color.Black), 130, 10); page.Canvas.DrawString("編號:31231", font1, new PdfSolidBrush(System.Drawing.Color.Black), 380, 60); page.Canvas.DrawString("經辦人:XXXX", font1, new PdfSolidBrush(System.Drawing.Color.Black), 60, 250); page.Canvas.DrawString("列印日期:2020/06/15", font1, new PdfSolidBrush(System.Drawing.Color.Black), 380, 250); //設定單元格邊距 grid.Style.CellPadding = new PdfPaddings(1, 1, 4, 4); //設定表格預設字型 grid.Style.Font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 12f), true); //新增4行4列 PdfGridRow row1 = grid.Rows.Add(); PdfGridRow row2 = grid.Rows.Add(); PdfGridRow row3 = grid.Rows.Add(); PdfGridRow row4 = grid.Rows.Add(); PdfGridRow row5 = grid.Rows.Add(); PdfGridRow row6 = grid.Rows.Add(); grid.Columns.Add(4); //設定列寬 foreach (PdfGridColumn col in grid.Columns) { col.Width = 120f; } //寫入資料 第一行第一個格式的值,第一行第二個格子的值 row1.Cells[0].Value = "收款單位"; row1.Cells[1].Value = "{DW}"; row2.Cells[0].Value = "收款單位"; row2.Cells[1].Value = "{DW}"; row3.Cells[0].Value = "匯款時間"; row3.Cells[1].Value = "2016/06/02"; row3.Cells[2].Value = "金額小寫"; row3.Cells[3].Value = "¥231"; row4.Cells[0].Value = "金額合計大寫"; row4.Cells[1].Value = "大蘇打實打實"; row5.Cells[0].Value = "用途:" + "付XXXX2020年04月至2020年04月"; row6.Cells[0].Value = "提示:回單可重複列印,請勿重複XXX"; //row5.Cells[0].Height = (float)20; //水平和垂直合併單元格 從那個格子開始合併幾個(包含當前格子) row1.Cells[1].ColumnSpan = 3; row2.Cells[1].ColumnSpan = 3; row4.Cells[1].ColumnSpan = 3; row5.Cells[0].ColumnSpan = 2; row5.Cells[2].ColumnSpan = 2; row6.Cells[0].ColumnSpan = 2; row6.Cells[2].ColumnSpan = 2; //這個是垂直合併,但是我之前合併的沒有效果 row5.Cells[1].RowSpan = 2; //設定單元格內文字對齊方式 row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row1.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row2.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row2.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row3.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row3.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row3.Cells[3].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row4.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row4.Cells[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row5.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); row6.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center); //設定單元格背景顏色 //row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Gray; //row3.Cells[3].Style.BackgroundBrush = PdfBrushes.Green; //row4.Cells[3].Style.BackgroundBrush = PdfBrushes.MediumVioletRed; //設定邊框顏色、粗細 PdfBorders borders = new PdfBorders(); borders.All = new PdfPen(System.Drawing.Color.Black, 0.1f); foreach (PdfGridRow pgr in grid.Rows) { foreach (PdfGridCell pgc in pgr.Cells) { pgc.Style.Borders = borders; } } //儲存到文件 //在指定為繪入表格 grid.Draw(page, new PointF(30, 80)); doc.SaveToFile(@"路徑"); //這句是在瀏覽器重開啟這個PDF System.Diagnostics.Process.Start(@"路徑"); }
儲存我們看一下
2、之後就是關於PDF一些轉換的操作了(PDF轉base64,轉圖片之類的,我把程式碼貼到下面)
- 這個用到了iTextSharp類庫,也可以在Nuget下載到
/// <summary> /// 圖片轉pdf /// </summary> /// <param name="jpgfile"></param> /// <param name="pdf"></param> public static bool ConvertJPG2PDF(string jpgfile, string pdf) { try { 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)) { PdfWriter.GetInstance(document, stream); 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.NewPage(); document.Add(image); } document.Close(); } return true; } catch (Exception ex) { throw ex; } }
- 這個用的是(O2S.Components.PDFRender4NET)
/// <summary> /// pdf轉img /// </summary> /// <param name="path">pdf位置</param> /// <param name="path2">img位置</param> public static void Pdf2Img(string path, string path2) { PDFFile pdfFile = PDFFile.Open(path); //例項化一個PdfDocument類物件,並載入PDF文件 using (Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument()) { doc.LoadFromFile(path); //呼叫方法SaveAsImage()將PDF第一頁儲存為Bmp格式 System.Drawing.Image bmp = doc.SaveAsImage(0); // //呼叫另一個SaveAsImage()方法,並將指定頁面儲存儲存為Emf、Png System.Drawing.Image emf = doc.SaveAsImage(0, Spire.Pdf.Graphics.PdfImageType.Bitmap); System.Drawing.Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2)); using (Graphics g = Graphics.FromImage(zoomImg)) { g.ScaleTransform(2.0f, 2.0f); g.DrawImage(emf, new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), emf.Size), new System.Drawing.Rectangle(new System.Drawing.Point(0, 0), emf.Size), GraphicsUnit.Pixel); zoomImg.Save(path2, ImageFormat.Jpeg); zoomImg.Dispose(); emf.Dispose(); bmp.Dispose(); } doc.Close(); doc.Dispose(); } }
- 這個和上面用的也是同一個(我覺得這個比較好用一些)
/// <summary> /// 將PDF文件轉換為圖片的方法 /// </summary> /// <param name="pdfInputPath">PDF檔案路徑</param> /// <param name="imageOutputPath">圖片輸出路徑</param> /// <param name="imageName">生成圖片的名字</param> /// <param name="startPageNum">從PDF文件的第幾頁開始轉換</param> /// <param name="endPageNum">從PDF文件的第幾頁開始停止轉換</param> /// <param name="imageFormat">設定所需圖片格式</param> /// <param name="definition">設定圖片的清晰度,數字越大越清晰</param> public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition) { PDFFile pdfFile = null; FileStream fs = null; try { fs = new FileStream(pdfInputPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); pdfFile = PDFFile.Open(fs); if (startPageNum <= 0) { startPageNum = 1; } if (endPageNum > pdfFile.PageCount) { endPageNum = pdfFile.PageCount; } if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; } string path = imageOutputPath + imageName + "1" + "." + imageFormat.ToString(); Logger.WriteLogs("PDFIMG:" + path); using (Bitmap pageImage = pdfFile.GetPageImage(0, 56 * (int)definition)) { if (!File.Exists(path)) { using (FileStream f = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { pageImage.Save(f, ImageFormat.Jpeg); pageImage.Dispose(); } } } fs.Flush(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { if (pdfFile != null) { pdfFile.Dispose(); } else if (fs != null) { fs.Close(); fs.Dispose(); } } } public enum Definition { One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10 }
- PDF轉Base64
-
/// <summary> /// pdf轉base64 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static string PdfWord_To_Base64(string filePath) { try { if (!string.IsNullOrWhiteSpace(filePath.Trim())) { FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate); byte[] bt = new byte[fileStream.Length]; fileStream.Read(bt, 0, bt.Length); fileStream.Close(); fileStream.Dispose(); return Convert.ToBase64String(bt); } else { return "請輸入正確的路徑"; } } catch (Exception ex) { throw ex; } }
我主要也就用到這些,之後在發現,我在往上加
連結: https://pan.baidu.com/s/16xEpLBJ3-8fGjNPyvHUSmA
提取碼: p9qi
這個是O2S.Components.PDFRender4NET的檔案,我看評論裡有問的,之前忘記發了,網上有的是收費的,Nuget裡面帶字尾的我沒用過。