欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.Net 对于PDF生成以及各种转换的操作

程序员文章站 2022-05-06 09:29:13
...

1、生成PDF

  这里用到了 Spire.Pdf    这个类库可以在NuGet里面搜索到.Net 对于PDF生成以及各种转换的操作,上面带个小红标的就是免费版本。  当然也可以去他们的官网,上面还有文档(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(@"路径");
        }

  保存我们看一下

  .Net 对于PDF生成以及各种转换的操作

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里面带后缀的我没用过。

相关标签: C#.NET基础