分類
發燒車訊

.Net 對於PDF生成以及各種轉換的操作

前段時間公司的產品,要做一個新功能,簽章(就是把需要的數據整理成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裏面帶後綴的我沒用過。

 

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※超省錢租車方案

※別再煩惱如何寫文案,掌握八大原則!

※回頭車貨運收費標準

※教你寫出一流的銷售文案?

※產品缺大量曝光嗎?你需要的是一流包裝設計!

※廣告預算用在刀口上,台北網頁設計公司幫您達到更多曝光效益