C#ASP.NET MVC从视图Rotativa或iTextSharp创建PDF?

时间:2017-04-24 20:02:36

标签: c# asp.net asp.net-mvc itext rotativa

我对从多种形式生成PDF非常不熟悉。 事实上,我从未使用任何编程语言生成PDF。现在我一直在为我想做的事尝试两种不同的方法。不幸的是,几天后我仍然没有发现如何做到这一点。

我有多个表单,数据预填充在3个不同的列表中,现在我想生成这个表单的PDF,我一直在使用Rotativa。不幸的是,一旦我调用该方法生成PDF,它就会生成视图的PDF,但数据却丢失了。使用iTextSharp,我可以拥有1个单一列表的数据,而不是所有这些数据,我也不知道是否可以使用iTextSharp将此PDF保存在服务器上。

Q1:我应该使用什么方法?你有什么建议?使用Rotativa或iTextSharp?

问题2:对于没有太多编程经验的人来说,这是否可行?或者我应该尝试寻找其他方法吗?我

问题3:我还在想办法吗?我更喜欢不使用第三方软件的方法。

2 个答案:

答案 0 :(得分:1)

public byte [] GetPDF(string pHTML){     byte [] bPDF = null;

MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(pHTML);

// 1: create object of a itextsharp document class
Document doc = new Document(PageSize.A4, 25, 25, 25, 25);

// 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);

// 3: we create a worker parse the document
HTMLWorker htmlWorker = new HTMLWorker(doc);

// 4: we open document and start the worker on the document
doc.Open();
htmlWorker.StartDocument();

// 5: parse the html into the document
htmlWorker.Parse(txtReader);

// 6: close the document and the worker
htmlWorker.EndDocument();
htmlWorker.Close();
doc.Close();

bPDF = ms.ToArray();

return bPDF;

}

答案 1 :(得分:0)

使用ITextSharp作为.NET PDF库,它允许您生成PDF(可移植文档格式)。

首先,需要在项目中添加iTextSharp的引用。

您可以使用包管理器获取iTextSharp引用,只需执行以下命令即可下载并添加引用。

PM>安装包iTextSharp

现在您需要创建一个方法,它将为您提供PDF内容的字节数组,因此我们的代码将是