5

Coding4Fun - 在 IFrame 內嵌顯示 PDF 文件

 3 years ago
source link: https://blog.darkthread.net/blog/view-pdf-in-iframe/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
在 IFrame 內嵌顯示 PDF 文件-黑暗執行緒

#黑輪的 Coding 日常

哈囉大家好我是黑輪,你今天寫 Code 了嗎?(仿一輪 Style)

閒來無事,試做了一個有趣小東西。

在網頁用一個 IFrame 內嵌 PDF 文件,點連結可切換檔案,操作起來像這樣:

程式還蠻簡單的,前端網頁放一個 IFrame 設 name="reader",兩個 <a> 連結指向 PDF 檔案 URL 並指定 target="reader"。另外我有用到之前介紹過的 CSS flex 佔滿剩餘高度技巧

<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8>
	<style>
	html,body { margin: 0; padding: 0; height: 100%; font-size: 10pt; }
	body { display: flex; flex-direction: column; }
	div { height: 25px ; padding: 12px; }
	iframe { flex-grow: 1; width: 100%; }
	a { 
	    background-color: #03A9F4; color: white;
		padding: 3px 12px; text-decoration: none;
		border-radius: 3px; text-shadow: 1px 1px 1px #333;
	}
	</style>
</head>
<body >
<div>
	<a href="view.aspx?doc=1" target="reader">ASP.NET 防駭指南</a> 
	<a href="view.aspx?doc=2" target="reader">被遺忘的文字利器—探索.NET Regular Expression 元件</a> 
</div>
<iframe  name="reader"></iframe>
</body>
</html>

後端部分我是用 ASPX 依參數傳回不同 PDF,寫法如下:

<%@Page Language="C#"%>
<script runat="server">
byte[] GeneratePdfContent(string id) 
{
	//從儲存服務取出 PDF,此處以讀檔模擬
	var filePath = id == "1" ? 
		"D:\\ASP.NET Security.pdf" :
		"D:\\dotNET Regular Expression.pdf";
	return System.IO.File.ReadAllBytes(filePath);
}
void Page_Load(object sender, EventArgs e) 
{
	Response.ContentType = "application/pdf";
	Response.BinaryWrite(GeneratePdfContent(Request["doc"]));
	Response.End();
}
</script>

試了一下,IE 嘛 A 通! 感動~ (記得要安裝 Acrobat Reader 或 Foxit Reader,IE 需要它們提供閱讀 PDF 的附加元件)

用這個小技巧可以快速把現成文件放進上網站,用最少成本達到「可線上檢閱」的目標,雖然效能跟體驗並不理想,在一些情境下(例如:「這功能我明天就要」、「我老闆說要而且不能加錢」)仍是可考量的解決方案,提供大家參考。

and has 2 comments

Comments

Post a comment

Comment
Name Captcha 52 - 21 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK