使用itextsharp将pdf流式传输到用户的浏览器
我试着在这里关注这篇文章: http : //www.4guysfromrolla.com/articles/030911-1.aspx
我在Services.asmx中有这个方法:
[WebMethod] public void CreatePdf() { // Create a Document object var document = new Document(PageSize.A4, 50, 50, 25, 25); // Create a new PdfWriter object, specifying the output stream var output = new MemoryStream(); var writer = PdfWriter.GetInstance(document, output); // Open the Document for writing document.Open(); // Create a new Paragraph object with the text, "Hello, World!" var welcomeParagraph = new Paragraph("Hello, World!"); // Add the Paragraph object to the document document.Add(welcomeParagraph); // Close the Document - this saves the document contents to the output stream document.Close(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=file.pdf"); HttpContext.Current.Response.BinaryWrite(output.ToArray()); }
这个jQuery代码在我的页面上:
$('a.download').click(function () { $.ajax({ type: "POST", url: "/Services.asmx/CreatePdf", data: '{}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { alert(result.d); } }); });
这应该创建一个pdf并将其流式传输到用户的浏览器。
当我点击类download
的链接时,我的网络方法被点击并且代码运行。 它只是不将pdf流式传输到浏览器。
如果我查看Firebug,它会发布到我的方法状态为200,我得到此响应:
%PDF-1.4% 20 obj streamx + r 25P 04WI 2P 5 1 BҸ4>>> /目录2 0 R / Parent 3 0 R >> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 obj endobj xref 0 7 0000000000 65535 f 0000000304 00000 n 0000000015 00000 n 0000000392 00000 n 0000000147 00000 n 0000000443 00000 n 0000000488 00000 n预告片<] >>%iText-5.3.5 startxref 646 %% EOF {“d”:null}
我在这里做错了吗?
Marc B是对的。 您需要使用pdf输出流来响应服务器端代码。
因此,请将下载链接指向一个新文件,例如PDFDownload.aspx,并将CreatePdf函数中的代码放在PDFDownload.aspx.cs的PageLoad中。
当您使用xmlhttprequest时,您似乎无法接收二进制数据。 (这就是jquery所做的)。 当你做一个标准a href link
form post
它应该工作。 因为响应类型由浏览器处理…
确保在服务器上设置匹配的标头…
contentDisposition = "attachment=\"" name ""; contentType = "application/pdf";
希望这可以帮助
我这样做,那样:
页面aspx.cs中的方法
[WebMethod()] public static string CreatePdf() { System.IO.MemoryStream ms = new System.IO.MemoryStream(); iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 30f, 30f, 30f, 30f); iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms); doc.Open(); doc.Add(new iTextSharp.text.Chunk("hello world")); doc.Close(); // convert ms to byte and Base64 return System.Convert.ToBase64String(ms.ToArray()); }
函数jQuery
$("#createPdf").click(function () { //call ajax $.ajax({ url: "main.aspx/CreatePdf", data: '{}', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", success: function (result) { //pdf var downloadpdf = $(''); $('body').append(downloadpdf); document.getElementById("downloadpdf").click(); $("#downloadpdf").remove(); }, error: function (req, status, error) { alert(error); } }); });
我希望它可以帮助别人!