. Net for PDF generation and various transformations

A few days ago, the company's products needed to do a new function, signature (that is, to organize the required data into a standard PDF file, and then stamp our seal on the server)

Then I looked for it on Baidu, and found that there were few class libraries for PDF, either for money, or for watermarks. The cracked version was not found.

Let's talk about how I generate PDF

1. Generate PDF

It's used here Spire.Pdf This class library can be found in NuGet, with a little red mark on it is the free version.   

Of course, you can go to their official website. There are documents on it( https://www.e-iceblue.cn/Introduce/Spire-PDF-NET.html).

Code (this is a test form I wrote myself)

  

public static void abc()
        {
            //establish PDF file
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

            //Add a page
            PdfPageBase page = doc.Pages.Add();
    //Set font
            PdfTrueTypeFont font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 20f), true);
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 11f), true);

            //Create a PdfGrid object
            PdfGrid grid = new PdfGrid();

        //The content of this paragraph is to display only some data in the table according to the coordinates. The first is the content, the second is the font, the third is the color, the fourth and the fifth are the coordinates
            page.Canvas.DrawString("XXXXXXXX Management center receipt",
                    font,
                    new PdfSolidBrush(System.Drawing.Color.Black), 130, 10);
            page.Canvas.DrawString("No.: 31231",
                    font1,
                    new PdfSolidBrush(System.Drawing.Color.Black), 380, 60);
            page.Canvas.DrawString("Handled by: XXXX",
                    font1,
                    new PdfSolidBrush(System.Drawing.Color.Black), 60, 250);
            page.Canvas.DrawString("Printing date: 2020/06/15",
                    font1,
                    new PdfSolidBrush(System.Drawing.Color.Black), 380, 250);
            //Set cell margins
            grid.Style.CellPadding = new PdfPaddings(1, 1, 4, 4);

            //Set table default font
            grid.Style.Font = new PdfTrueTypeFont(new System.Drawing.Font("Microsoft Yahei", 12f), true);

            //Add 4 rows and 4 columns
            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);

            //Set column width
            foreach (PdfGridColumn col in grid.Columns)
            {
                col.Width = 120f;
            }

            //Write the value of the first format in the first row of data, and the value of the second cell in the first row 
            row1.Cells[0].Value = "Payee";
            row1.Cells[1].Value = "{DW}";
            row2.Cells[0].Value = "Payee";
            row2.Cells[1].Value = "{DW}";
            row3.Cells[0].Value = "remittance date";
            row3.Cells[1].Value = "2016/06/02";
            row3.Cells[2].Value = "Amount in figures";
            row3.Cells[3].Value = "¥231";
            row4.Cells[0].Value = "Total amount in words";
            row4.Cells[1].Value = "Baking soda";
            row5.Cells[0].Value = "purpose:" +
                "pay XXXX2020 April, 2020 to April, 2020";
            row6.Cells[0].Value = "Tips:Receipt can be printed repeatedly, please do not repeat XXX";

            //row5.Cells[0].Height = (float)20;
            //Merge cells horizontally and vertically merge several cells (including the current cell) from that cell
            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;
        //This is a vertical merge, but what I merged before has no effect
            row5.Cells[1].RowSpan = 2;

            //Set text alignment within cells
            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);
            //Set cell background color
            //row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Gray;
            //row3.Cells[3].Style.BackgroundBrush = PdfBrushes.Green;
            //row4.Cells[3].Style.BackgroundBrush = PdfBrushes.MediumVioletRed;

            //Set border color and thickness
            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;
                }
            }
            //Save to document
            //When specified as draw in table
            grid.Draw(page, new PointF(30, 80));
            doc.SaveToFile(@"route");
       //This sentence is to reopen this in the browser PDF  
            System.Diagnostics.Process.Start(@"route");
        }

 

Save. Let's take a look

  

 

 

2. Then there are some conversion operations about PDF (PDF to base64, to pictures and so on, I paste the code below)

 

 

 

  • This uses the iTextSharp class library, which can also be downloaded to Nuget

 

/// <summary>
        /// Picture transfer 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;
            }
        }
  • This one uses (o2s Components.PDFRender4NET )
/// <summary>
        /// pdf turn img
        /// </summary>
        /// <param name="path">pdf position</param>
        /// <param name="path2">img position</param>
        public static void Pdf2Img(string path, string path2)
        {
            PDFFile pdfFile = PDFFile.Open(path);
            //item base  PdfDocument Class object, and load PDF file
            using (Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument())
            {
                doc.LoadFromFile(path);
                //Call method SaveAsImage()take PDF First page saved as Bmp format
                System.Drawing.Image bmp = doc.SaveAsImage(0);
                // //Call another SaveAsImage()Method and save the specified page as 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();
            }
            
           
        }
  • This one is the same as the one used above (I think this one is easier to use)

 

/// <summary>
                /// take PDF How to convert a document to a picture
                /// </summary>
                /// <param name="pdfInputPath">PDF File path</param>
                /// <param name="imageOutputPath">Picture output path</param>
                /// <param name="imageName">Name of the generated image</param>
                /// <param name="startPageNum">from PDF Page number of the document to start conversion</param>
                /// <param name="endPageNum">from PDF Page number of the document begins to stop conversion</param>
                /// <param name="imageFormat">Format the desired picture</param>
                /// <param name="definition">Set the sharpness of the picture, the bigger the number, the clearer</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 to Base64
  • /// <summary>
            /// pdf turn 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 "please enter a correct path";
                    }
    
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

    I mainly use these. Later, I found that I was adding

Link: https://pan.baidu.com/s/16xEpLBJ3-8fGjNPyvHUSmA

Extraction code: p9qi

This is o2s Components.PDFRender4NET I've seen some of the documents in the comments. I forgot to send them before. There are charges on the Internet. I haven't used the suffixes in Nuget.

Posted on Wed, 17 Jun 2020 05:27:08 -0400 by ulrikqk