[ASP.NET,iTextSharp]用程式直接列印pdf

  • 8631
  • 0
  • 2016-03-24

[ASP.NET,MVC,iTextSharp]用程式直接列印pdf

在.net裡面,用程式碼直接列印pdf的方式在不同種類的應用程式就會有不同的作法。
如果是在Winform, console等應用程式的話,直接參考此文章[ASP.NET,iTextSharp]用程式呼叫cmd(command line)執行exe(以開啟adobe reader列印pdf為例)即可。
但如果是在web架構的應用程式(ex:asp.net web form 或是asp.net mvc)的話,就需要改用另外的作法,因為在網路應用程式是架構在IIS底下的,要透過IIS去呼叫exe執行檔的話,通常會需要在IIS的應用程式集區另外設定相關權限,因此web架構的應用程式就得採用javascript的print()來做列印會比較好,以下就開始介紹web的作法:

1.ASP.NET WEB FORM:
主要的原理就是利用iTextSharp在pdf加入javascript的功能,並且在javascript中執行print()指令來執行列印指令,如果在ie開啟這個網頁,就會開啟adobe reader的列印視窗,如果是在chrome開啟這個網頁,就會在chrome直接產生列印的視窗。
.aspx.cs(這個檔案是位於ApplicationPath根目錄下的):

protected void testPrintBtn1_Click(object sender, EventArgs e)
{
	
	Document doc = new Document(PageSize.A8);
	PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Request.PhysicalApplicationPath + "WebFormPdf.pdf", FileMode.Create));
	doc.Open();

	//在pdf加入這個javascript之後,只要打開此pdf就會啟動adobe reader列印的指令
	PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
	writer.AddJavaScript(jAction);

	doc.Add(new Paragraph("when open this pdf, the printer will start to print!!"));
	doc.Close();

	//將iframe的來源帶入此pdf
	frame1.Attributes["src"] = "WebFormPdf.pdf";

}

.aspx(這個檔案是位於ApplicationPath根目錄下的):

<asp:Button ID="testPrintBtn1" runat="server" Text="測試列印1" OnClick="testPrintBtn1_Click" />
<iframe id="frame1" runat="server" style="display:none;" ></iframe>


chrome執行結果:會利用chrome內建的列印介面去列印。

IE執行結果:會呼叫adobe reader的介面作列印。
以上是asp.net web form直接呼叫pdf列印的方式。

2.ASP.NET MVC:
原理跟ASP.NET WEB FORM幾乎一樣,差別就在於View所在的路徑都會包在一層Controller的名稱之下(例如:HomeController.cs對應的view將會是~/Views/Home/Index.cshtml),因此iframe的src的檔案路徑就要稍做修改一下。
Controller - HomeController.cs:

public class HomeController : Controller
{
	//
	// GET: /Home/

	public ActionResult Index()
	{
		//do nothing
		return View();
	}


	public ActionResult IndexDownloadFile()
	{
		Document doc = new Document(PageSize.A8);
		PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Request.PhysicalApplicationPath + "MVC.pdf", FileMode.Create));
		doc.Open();

		//在pdf加入這個javascript之後,只要打開此pdf就會啟動adobe reader列印的指令
		PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
		writer.AddJavaScript(jAction);

		doc.Add(new Paragraph("when open this pdf, the printer will start to print!!"));
		doc.Close();

		//將iframe的來源帶入此pdf
		//由於產出的pdf的路徑預設是在 application path, 
		//而目前Index這個view並不在同一個路徑下,因此需要調整到上上層目錄
		ViewBag.iframeSrc = "../../MVC.pdf";
		return View("Index");
	}

}

View - Index.cshtml:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<input type="button" value="測試列印" onclick="location.href='@Url.Action("IndexDownloadFile", "Home")'" />

<iframe style="display:none;" src="@ViewBag.iframeSrc"></iframe>

產出的pdf結果由於跟asp.net web forms的一樣,因此就不再重複貼上囉。

參考資料:
http://stackoverflow.com/questions/270674/print-pdf-from-asp-net-without-preview
http://stackoverflow.com/questions/2503923/html-button-calling-a-mvc-controller-and-action-method