以下为在.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

.net生成PDF文件的几种方式的更多相关文章

  1. 使用ABAP和JavaScript代码生成PDF文件的几种方式

    ABAP 方法1:使用ABAP + Adobe Lifecycle Enterprise Service 详细步骤参考我的博客Convert word document into PDF via Ad ...

  2. pdfjs预览pdf文件的两种方式(可复制)

    1.以图片形式进行展示: version:采用1.x版本,2.0版本会有字体显示不完整的问题:参考 这里使用1.8.170 <script th:src="@{/pdfjs/build ...

  3. java调用wkhtmltopdf生成pdf文件,美观,省事

    最近项目需要导出企业风险报告,文件格式为pdf,于是搜了一大批文章都是什么Jasper Report,iText ,flying sauser ,都尝试了一遍,感觉不是我想要的效果, 需要自己调整好多 ...

  4. Itext生成pdf文件

    来源:https://my.oschina.net/lujianing/blog/894365 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等. ...

  5. 在spring boot 中使用itext和itextrender生成pdf文件

    转载请注明出处 https://www.cnblogs.com/majianming/p/9539376.html 项目中需要对订单生成pdf文件,在第一版本其实已经有了比较满意的pdf文档,但是还是 ...

  6. Java生成PDF文件(转)

    原文地址:https://www.cnblogs.com/shuilangyizu/p/5760928.html 一.前言 前几天,做ASN条码收货模块,需要实现打印下载收货报表,经一番查找,选定iT ...

  7. [itext]Java生成PDF文件

    一.前言 最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错.最后想到直接将文件写入pdf(参考:http://www.c ...

  8. Asciidoctor-pdf生成pdf文件

    本文使用asciidoc语法编写. = Asciidoctor-pdf生成pdf文件 Pinnsvin Pinnsvin@163.com v1.0 {docdate} :plantuml-server ...

  9. 前端js,css文件合并三种方式,bat命令

    前端js,css文件合并三种方式,bat命令 前端js文件该如何合并三个方式如下:1. 一个大文件,所有js合并成一个大文件,所有页面都引用它.2. 各个页面大文件,各自页面合并生成自己所需js的大文 ...

随机推荐

  1. 15、WAN

    WAN wide area network 覆盖较大地理范围的数据通信网络使用网络提供商和电信公司所提供的传输设施传输数据 通过不同WAN协议,将LAN延伸到远程站点的其他LAN广域网接入处于OSI七 ...

  2. NLP(二十)利用BERT实现文本二分类

      在我们进行事件抽取的时候,我们需要触发词来确定是否属于某个特定的事件类型,比如我们以政治上的出访类事件为例,这类事件往往会出现"访问"这个词语,但是仅仅通过"访问&q ...

  3. CSAPP

    陆陆续续花了2个月的时间终于把这个久负盛名的CSAPP看完了,不愧为一本名副其实的经典书籍.有种相见恨晚的感觉,以至于从不会写书评的我也情不自禁的想说点什么.  这本书的书名叫"Comput ...

  4. 仅仅知道如何终止XHR请求,或许对你来说是不够的!

    TLDR: 当我们需要的时候,我们可以通过AbortController接口来终止一个或者多个请求. 前言 到目前为止,我们有两个常用的基本的手段去发送请求进而局部刷新页面内容,其一是XMR(XMLH ...

  5. javascript原生js轮播图

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. python使用turtle库绘制奥运五环

    效果图: #奥运五环 import turtle turtle.setup(1.0,1.0) #设置窗口大小 turtle.title("奥运五环") #蓝圆 turtle.pen ...

  7. TCP三次握手四次挥手过程梳理

    1. 数据传输的大致示意图 1.1 TCP数据报文首部内部 1.2 TCP连接的几种状态说明 即命令 netstat 结果中的所有状态: 2. TCP连接建立的全过程 2.1 TCP三次握手建立TCP ...

  8. Linux安装Redis,在测试阶段即make test出现“You need tcl 8.5 or newer in order to run the Redis test”问题解决方案

    Linux安装Redis,在测试阶段即make test出现"You need tcl 8.5 or newer in order to run the Redis test"问题 ...

  9. http报文解析

    http报文结构 报文首部 起始行 请求报文的起始行: 方法(method) request-URL version(http协议版本) 响应报文的起始行 HTTP响应码 请求头 通用首部 请求首部 ...

  10. 嗅探、DNS劫持配合CS钓鱼

    本章节讲述的是嗅探和DNS劫持的利用 嗅探:同一个局域网下,原本应该丢弃的包,被保留下来,即使不开双向欺骗 Driftnet工具:Driftnet监视网络流量,抓取网络流量中的JPEG和GIF图像.这 ...