从ASP.Net打印PDF无需预览

我使用iTextSharp生成了一个pdf,我可以在ASP.Net中很好地预览它,但我需要将它直接发送到打印机而不进行预览。 我希望用户单击打印按钮并自动打印文档。

我知道可以使用javascript window.print()将页面直接发送到打印机,但我不知道如何为PDF创建它。

编辑:它没有嵌入,我这样生成它;

... FileStream stream = new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create); Document pdf = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(pdf, stream); pdf.Open(); pdf.Add(new Paragraph(member.ToString())); pdf.Close(); Response.Redirect("~1.pdf"); ... 

而我在这里。

最后我做了,但是我不得不使用IFRAME,我在aspx中定义了一个IFrame而没有设置src属性,在cs文件中我生成了pdf文件并将iFrame的src属性设置为生成pdf文件名,像这样;

 Document pdf = new Document(PageSize.LETTER); PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create)); pdf.Open(); //This action leads directly to printer dialogue PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); pdf.Add(new Paragraph("My first PDF on line")); pdf.Close(); //Open the pdf in the frame frame1.Attributes["src"] = "~1.pdf"; 

然而,这就是诀窍,我认为我应该实现你的解决方案Stefan,问题是我是asp.net和javascript的新手,如果我没有完整的源代码,我就无法编写你的建议但是至少是第一步,我很惊讶我需要学习多少html和javascript代码。 日Thnx。

pdf是否嵌入到带有embedd-tag的页面中,或者只是在框架中打开,或者您是如何显示的?

如果它是嵌入的,只需确保选中对象然后执行print()。

获取嵌入文档的参考。

 var x = document.getElementById("mypdfembeddobject"); x.click(); x.setActive(); x.focus(); x.print(); 

如果你使用pdfsharp但是非常可行,这会有点棘手

 PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx = XGraphics.FromPdfPage(page); XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic); // Draw the text gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center); // real stuff starts here // current version of pdfsharp doesn't support actions // http://www.pdfsharp.net/wiki/WorkOnPdfObjects-sample.ashx // so we got to get close to the metal see chapter 12.6.4 of // http://partners.adobe.com/public/developer/pdf/index_reference.html PdfDictionary dict = new PdfDictionary(document); // dict.Elements["/S"] = new PdfName("/JavaScript"); // dict.Elements["/JS"] = new PdfString("this.print(true);\r"); document.Internals.AddObject(dict); document.Internals.Catalog.Elements["/OpenAction"] = PdfInternals.GetReference(dict); document.Save(Server.MapPath("2.pdf")); frame1.Attributes["src"] = "2.pdf"; 

另外,试试这个gem:

  

我还没有对它进行过测试,但是我已经读过它,它可以用这种方式打印mypdf.pdf而不是页面内容,无论你用什么方法打印页面。

搜索media =“print”以查看更多信息。

您可以在pdf中嵌入javascript,以便用户在浏览器加载pdf后立即获得打印对话框。

我不确定iTextSharp,但我使用的是javascript

 var pp = this.getPrintParams(); pp.interactive = pp.constants.interactionLevel.automatic; this.print(pp); 

对于iTextSharp,请查看http://itextsharp.sourceforge.net/examples/Chap1106.cs