.net generate PDF files in several ways

Following is a .net mvc, the generated pdf in several ways, all the information when doing the project find online

1, the use of the word to PDF Microsoft.Office.Interop.Word.dll

dll can be downloaded separately, generally have in the computer, location: C: \ Windows \ Microsoft.NET \ Framework \ v4.0.30319 \ Temporary ASP.NET Files \ vs \ 199bd4f2 \ edef3bc1 \ assembly \ dl3 \ 60e90863 \ 53bea978_07e9d401 \ Microsoft. Office.Interop.Word.DLL

public bool WordToPdf(object sourcePath, string targetPath)
        {
            bool result = false;
            WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;
            object missing = Type.Missing;
            Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;
            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
                document = applicationClass.Documents.Open(ref sourcePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                if (document != null)
                {
                    document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (document != null)
                {
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                }
                if (applicationClass != null)
                {
                    applicationClass.Quit(ref missing, ref missing, ref missing);
                    applicationClass = null;
                }
            }
            return result;
        }

  use

public FileResult Demo()
        {
            string wordPath = Server.MapPath(@"\TempFile\Word\Test.docx");
            string pdfPath = Server.MapPath(@"\TempFile\PDF\Test.pdf");

            WordToPdf(wordPath, pdfPath);

            FileStream fs = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);
            byte[] fileContents = new byte[(int)fs.Length];
            fs.Read(fileContents, 0, fileContents.Length);
            fs.Close();

            return File(fileContents, "application/pdf", "test.pdf");
        }

  2, itextsharp generate PDF

nuget find itextsharp, and add item

FileResult ItextSharpDemo public () 
        { 
            String filename = the Server.MapPath (@ "\ TempFile \ PDF \ ItextSharpTest.pdf"); 

            iTextSharp.text.Rectangle new new iTextSharp.text.Rectangle the pageSize = (1000, 500); 
            iTextSharp.text.Document = new new iTextSharp.text.Document document (the pageSize, 10, 10, 10, 10); 
            the PdfWriter Writer = PdfWriter.GetInstance (document, new new the FileStream (filename, FileMode.Create)); 
            document.open (); 

            // set document Related information 
            document.AddTitle ( "this is the title"); 
            document.AddSubject ( "theme"); 
            document.AddKeywords ( "keyword"); 
            document.AddCreator ( "creator"); 
            the Document.AddAuthor ( "Author");

            //添加内容
            document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " + "这是中文"));
            
            //添加图片
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath(@"\images\1.png"));
            img.SetAbsolutePosition(100, 50);
            writer.DirectContent.AddImage(img);

            img = iTextSharp.text.Image.GetInstance(Server.MapPath(@"\images\2.png"));
            img.SetAbsolutePosition(200, 50);
            writer.DirectContent.AddImage(img);

            img = iTextSharp.text.Image.GetInstance(Server.MapPath(@"\images\3.png"));
            img.SetAbsolutePosition(300, 50);
            writer.DirectContent.AddImage (img);

            document.Close();
            writer.Close();

            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            byte[] fileContents = new byte[(int)fs.Length];
            fs.Read(fileContents, 0, fileContents.Length);
            fs.Close();

            return File(fileContents, "application/pdf", "test.pdf");
        }

  Source is the lower left corner, the calculated position is inconvenient

3, Rotativa will generate html and pdf download

nuget find Rotativa, and add item

public ActionResult DemoViewAsPdf()
        {
            return new ViewAsPdf("DemoViewAsPdf");
            //return new ActionAsPdf("DemoViewAsPdf")
            //{ FileName = "demo.pdf" };
        }

  4, PDFSharp generated pdf

nuget find PDFSharp, and add item

/// <the Summary> 
        /// 1, when used inside windows fonts, error 
        /// 2, the default does not support Chinese 
        /// </ the Summary> 
        public void CreatePDF () 
        { 
            // Create a new PDF document 
            PdfDocument document new new PDFDocument = (); 

            // create an empty page 
            PdfPage page = document.AddPage (); 

            // set up a canvas 
            XGraphics gfx = XGraphics.FromPdfPage (page); 

            // set the font unit: PX 
            //System.Drawing.Text. pfcFonts = new new System.Drawing.Text.PrivateFontCollection the PrivateFontCollection (); 
            // String strFontPath = @ "C: /Windows/Fonts/msyh.ttc"; // font is set to Microsoft elegant black 
            //pfcFonts.AddFontFile(strFontPath);

            //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            //XFont font = new XFont(pfcFonts.Families[0], 15, XFontStyle.Regular, options);

            System.Drawing.Text.PrivateFontCollection pfcFonts = new System.Drawing.Text.PrivateFontCollection();
            string strFontPath = @"C:/Windows/Fonts/msyh.ttc";//字体设置为微软雅黑 
            pfcFonts.AddFontFile(strFontPath);

            XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            XFont font = new XFont(pfcFonts.Families[0], 20, XFontStyle.Bold, options);

            // 设置(添加)文本
            gfx.DrawString("Hello, World!", font, XBrushes.Black,
              new XRect(0, 0, page.Width, page.Height),
              XStringFormat.TopLeft); 

            // Picture 
            String imgpath = Server.MapPath (@ "\ ImagesRF Royalty Free \ 1.png"); 

            XImage Image = XImage.FromFile (imgpath); 
            // Double the X-= (gfx.PageSize.Width - Image. 72 * PixelWidth / image.HorizontalResolution) / 2; 
            // Double Y = (gfx.PageSize.Height - image.PixelHeight * 72 / image.VerticalResolution) / 2; 
            gfx.DrawImage (Image, 10, 30); 

            // set (add) a text 
            //gfx.DrawString("123124121 ", font, XBrushes.Black, 
            // new new XRect (0, 0, page.Width, page.Height) 
            // save the document
            //  );
            gfx.DrawString ( "This is a line of Chinese", font, XBrushes.Black, 0, + 60 image.PixelHeight); 

            String filename = the Server.MapPath (@ "\ the tempfile \ HelloWorld.pdf"); 
            Document.Save (filename) ; 
        }

  5、Spire.Pdf

nuget find Spire.Pdf, and add item

void CreatePDF public () 
        { 
            PDFDocument Document PDFDocument new new = (); 
            
            // for converting various sizes 
            PdfUnitConvertor unitCvtr new new PdfUnitConvertor = (); 

            // for setting margins 
            PdfMargins margins new new PdfMargins = (); 

            // Set the page margins unit: lb / point 
            margins.Top = unitCvtr.ConvertUnits (20f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point); 
            margins.Bottom = margins.Top; 
            margins.Left = 0; 
            margins.Right = margins.Left; 
            
            // Add a new A4-sized page, A4 size is 297mm * 211mm 
            PdfPageBase page = document.Pages.Add (PdfPageSize.A4, margins);
             
            // font, font size, font set the font size in units of pounds
            PdfTrueTypeFont titleFont = new PdfTrueTypeFont (new Font ( " Arial", unitCvtr.ConvertUnits (24f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)), to true); 
            PdfTrueTypeFont contentFont new new PdfTrueTypeFont = (new new the Font ( "Arial", unitCvtr.ConvertUnits (14f , PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)), to true); 

            // font color 
            // PdfPen as hollow words 
            // PdfPen PEN = new new PDFpen (Color.Black); 
            PdfBrush Brush = new new PdfSolidBrush (Color.Black); 

            // writing content, x is the distance from the left, in pounds, y is the distance from the above, in pounds 
            string text = ( "here title"); 
            page.Canvas.DrawString (text, titleFont, Brush, unitCvtr. ConvertUnits (14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), 0); 

            text = ( "Here is the content ");
            page.Canvas.DrawString (text, contentFont, Brush, unitCvtr.ConvertUnits (14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), unitCvtr.ConvertUnits (30f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)); 

            text = ( "Content here 2 "); 
            page.Canvas.DrawString (text, contentFont, Brush, unitCvtr.ConvertUnits (14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), unitCvtr.ConvertUnits (50f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)); 

            // press specified address load picture 
            PdfImage Image = PdfImage.FromFile (Server.MapPath (@ "\ ImagesRF Royalty Free \ 1.png")); 

            // load picture by picture stream 
            // Image img; 
            // PdfImage img = PdfImage.FromImage (img) 

            // stream stream by load picture 
            //System.IO.Stream stream;
            IMG = PdfImage.FromStream PdfImage // (Stream) 

            a float image.width * width = 0.55F; 
            a float image.height * height = 0.55F; 

            a float unitCvtr.ConvertUnits Y = ((20f + 30f + 20f), PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point); 

            // insert images, x is the distance from the left, in pounds, y is the distance from the above, in pounds, width, height of a write PDF image width and height in pixels 
            page.Canvas.DrawImage (Image, unitCvtr.ConvertUnits (14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), the y-, width, height); 

            // save and open the document 
            document.SaveToFile (Server.MapPath (@ "\ tempfile \ PDF creation .pdf") ); 
            //System.Diagnostics.Process.Start("PDF create .pdf "); 
        }

  Spire.Pdf is the only thing I did not encounter Chinese garbled when testing plug-in, and the source in the upper left corner, and provide unit conversion tools, so personally prefer Spire.Pdf

Guess you like

Origin www.cnblogs.com/zhoushangwu/p/11666637.html