以下為在.net mvc中,生成pdf的幾種方式,資料都是在做項目時網上找的
1、使用Microsoft.Office.Interop.Word.dll將word轉換為PDF
dll可以單獨下載,一般在電腦中有,位置: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; }
使用
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生成PDF
nuget中查找itextsharp,並加入項目
public FileResult ItextSharpDemo() { string filename = Server.MapPath(@"\TempFile\PDF\ItextSharpTest.pdf"); iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(1000, 500); iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize, 10, 10, 10, 10); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); //設置文檔相關信息 document.AddTitle("這里是標題"); document.AddSubject("主題"); document.AddKeywords("關鍵字"); document.AddCreator("創建者"); document.AddAuthor("作者"); //添加內容 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"); }
源點為左下角,不方便計算位置
3、Rotativa將html生成pdf並下載
nuget中查找Rotativa,並加入項目
public ActionResult DemoViewAsPdf() { return new ViewAsPdf("DemoViewAsPdf"); //return new ActionAsPdf("DemoViewAsPdf") //{ FileName = "demo.pdf" }; }
4、PDFSharp生成pdf
nuget中查找PDFSharp,並加入項目
/// <summary> /// 1、使用windows里面的字體時,報錯 /// 2、默認不支持中文 /// </summary> public void CreatePDF() { // 創建新的PDF文檔 PdfDocument document = new PdfDocument(); // 創建空頁 PdfPage page = document.AddPage(); // 設置一個畫布 XGraphics gfx = XGraphics.FromPdfPage(page); // 設置字體 單位:px //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], 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); // 圖片 string imgPath = Server.MapPath(@"\images\1.png"); XImage image = XImage.FromFile(imgPath); //double x = (gfx.PageSize.Width - image.PixelWidth * 72 / image.HorizontalResolution) / 2; //double y = (gfx.PageSize.Height - image.PixelHeight * 72 / image.VerticalResolution) / 2; gfx.DrawImage(image, 10, 30); // 設置(添加)文本 //gfx.DrawString("123124121", font, XBrushes.Black, // new XRect(0, 0, page.Width, page.Height) // ); gfx.DrawString("這是一行中文", font, XBrushes.Black, 0, 60 + image.PixelHeight); // 保存文檔 string filename = Server.MapPath(@"\tempfile\HelloWorld.pdf"); document.Save(filename); }
5、Spire.Pdf
nuget中查找Spire.Pdf,並加入項目
public void CreatePDF() { PdfDocument document = new PdfDocument(); //用於轉換各種尺寸 PdfUnitConvertor unitCvtr = new PdfUnitConvertor(); //用於設置頁邊距 PdfMargins margins = new PdfMargins(); //設置頁邊距 單位:磅/點 margins.Top = unitCvtr.ConvertUnits(20f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point); margins.Bottom = margins.Top; margins.Left = 0; margins.Right = margins.Left; //新添加一個A4大小的頁面,A4大小為211mm*297mm PdfPageBase page = document.Pages.Add(PdfPageSize.A4, margins); //字體,字體大小,font中設置字體大小的單位為磅 PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("宋體", unitCvtr.ConvertUnits(24f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)), true); PdfTrueTypeFont contentFont = new PdfTrueTypeFont(new Font("宋體", unitCvtr.ConvertUnits(14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)), true); //字體顏色 //PdfPen為空心字 //PdfPen pen = new PdfPen(Color.Black); PdfBrush brush = new PdfSolidBrush(Color.Black); //寫入內容,x為距離左邊的距離,單位為磅,y為距離上面的距離,單位為磅 string text = ("這里是標題"); page.Canvas.DrawString(text, titleFont, brush, unitCvtr.ConvertUnits(14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), 0); text = ("這里是內容"); page.Canvas.DrawString(text, contentFont, brush, unitCvtr.ConvertUnits(14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), unitCvtr.ConvertUnits(30f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)); text = ("這里是內容2"); page.Canvas.DrawString(text, contentFont, brush, unitCvtr.ConvertUnits(14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), unitCvtr.ConvertUnits(50f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)); //按指定地址加載圖片 PdfImage image = PdfImage.FromFile(Server.MapPath(@"\images\1.png")); //按圖片流加載圖片 //Image img; //PdfImage img = PdfImage.FromImage(img) //按Stream流加載圖片 //System.IO.Stream stream; //PdfImage img = PdfImage.FromStream(stream) float width = image.Width * 0.55f; float height = image.Height * 0.55f; float y = unitCvtr.ConvertUnits((20f+30f+20f), PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point); //插入圖片,x為距離左邊的距離,單位磅,y為距離上面的距離,單位磅,width,height為寫入PDF的圖片的寬高,單位像素 page.Canvas.DrawImage(image, unitCvtr.ConvertUnits(14f, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point), y, width, height); //保存並打開文檔 document.SaveToFile(Server.MapPath(@"\tempfile\PDF創建.pdf")); //System.Diagnostics.Process.Start("PDF創建.pdf"); }
Spire.Pdf是我在測試時唯一沒有遇到中文亂碼的插件,而且源點在左上角,並提供單位轉換工具類,所以個人更喜歡Spire.Pdf