我正在尝试通过基于HTML生成PDF来创建“报告”。
首先,我只是尝试将原始编码的HTML写入文档,然后使用Javascript打印该文档。但是,这让我几乎没有涉及页眉和页脚的控制。
我尝试使用thead
和tfoot
元素,这些元素在大多数浏览器中运行得相当不错,但是我无法获得我想要的格式。
目前 - 我正在尝试使用MVC3中的iTextSharp处理服务器端解决方案,但是我对如何继续工作感到有些迷茫,因为没有使用iTextSharp。
输出的输入和说明:
创建报告时将使用4个项目:
控制器操作:
//This will be accessed by a jQuery Post
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
//Grab Report Item
ReportClass report = reportingAgent.GetReportById(id);
Document doc = new Document();
//Do I need to decode the HTML or is it possible to use the encoded HTML?
//Adding Headers / Footers
//Best method of returning the PDF?
}
答案 0 :(得分:2)
iTextSharp无法将HTML转换为PDF。这不是它的设计目的。它旨在从头开始创建PDF文件,而不是在各种格式之间转换为PDF。如果您想将HTML转换为PDF,您可以使用基于iText
的{{3}}库。我有flying-saucer关于如何使用blogged在.NET中完成此操作。
所以你的控制器动作可能看起来像是:
[HttpPost]
public FileStreamResult GeneratePDF(string id)
{
ReportClass report = reportingAgent.GetReportById(id);
return PdfResult(report.Html);
}
其中PdfResult
可以是自定义操作结果,采用原始HTML并将PDF输出到响应流中:
public class PdfResult : ActionResult
{
private readonly string _html;
public PdfResult(string html)
{
_html = html;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
using (var bais = new ByteArrayInputStream(Encoding.UTF8.GetBytes(_html)))
using (var bao = new ByteArrayOutputStream())
{
var doc = builder.parse(bais);
var renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(bao);
var buffer = bao.toByteArray();
response.OutputStream.Write(buffer, 0, buffer.Length);
}
}
}