小弟这两天用itextsharp生成pdf文档,生成的pdf可以直接保存在指定路径的文件夹下,可是user不想保存,想要点一下button,就可以直接打印,我搞了半天也没找到合适的方法,还希望有做过这方面的,给些建议.多谢多谢啦
我的代码是这样的: iTextSharp.text.Rectangle page = new Rectangle(683,850);
iTextSharp.text.Document document = new iTextSharp.text.Document(page, 71, 43, 60, 28);
try
{
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream("C:\\" + DateTime.Now.ToString("yyyyMMdd") +
".pdf", FileMode.Create));
document.Open();
//我增加的文档内容部分
}
catch (Exception e)
{
}
// close the document
document.Close();
}
解决方法:
我把我的解决办法也贴出来吧,
1,把生成PDF文档到MemoryStream.
MemoryStream pdfdata = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, pdfdata);
2,在PdfWriter中加javescript.
StringBuilder script = new StringBuilder();
script.Append("this.print({bUI: true,bSilent: true,bShrinkToFit: false});");
writer.ViewerPreferences = PdfWriter.HideMenubar | PdfWriter.HideToolbar | PdfWriter.HideWindowUI;
writer.AddJavaScript(script.ToString());
3,输出到客户端缓存.
protected void submit_Click(object sender, EventArgs e)
{
MemoryStream PDFData =1中的返回值;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.AddHeader("Content-Disposition",
"inline; filename=" + Title.Replace(" ", "").Replace(":", "-") + ".pdf");
Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
}
4,我在页面上放一个iframe(width=0,height=0),就是让他不可见,让pdf文档在他下面打开,就会执行打印动作.
<form id="form1" runat="server" target="iframe1">
<div><center>
<br />
<asp:Button ID="submit" runat="server" OnClick="submit_Click" Text="Print PO" />
</center></div>
</form>
<iframe name="iframe1" width="0" height="0">
</iframe>
希望对想和我实现一样功能的朋友有些参考价值.