ASP.NET无需预览即可打印PDF

16
我使用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");
...

我来了。

5个回答

6

最终我成功了,但是我不得不使用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代码。谢谢。


1

PDF是通过嵌入标签嵌入到页面中的,还是在框架中打开,或者您是如何展示它的?

如果是嵌入的,请确保选择了该对象,然后执行print()。

获取嵌入文档的引用。

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

1

如果你正在使用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"; 

0

另外,试试这个宝石:

<link ref="mypdf" media="print" href="mypdf.pdf">

我还没有测试过它,但是根据我所读到的,它可以用于让mypdf.pdf被打印,而不管你使用什么方法来打印页面内容。

搜索media="print"以了解更多信息。


我发现这种方法在IE8上打印出了空白页。 - Martin Clarke
好主意,但我无法让它工作。Chrome和FF都忽略它,而IE9则会显示一个空白页面。 - Cavyn VonDeylen

0

您可以在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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接