ASP.NET MVC 是一种在 ASP.NET 框架下使用的 Web 应用程序框架。我们可以通过 ASP.NET MVC 将应用程序分为三个主要部分: 模型(Model)、视图(View)和控制器(Controller)。在 ASP.NET MVC 项目中,如果需要直接预览 PDF 文件,我们可以通过以下步骤来实现:
1. 生成 PDF 文件
我们可以使用第三方库来生成 PDF 文件,例如 iTextSharp,PdfSharp 或 Wkhtmltopdf。这里以 iTextSharp 为例,示例代码如下:
public ActionResult GeneratePdf()
{
Document document = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Paragraph paragraph = new Paragraph("Hello World!");
document.Add(paragraph);
document.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
return File(bytes, "application/pdf");
}
在上述代码中,我们首先创建一个文档对象 Document,然后创建一个内存流 MemoryStream,并将其与 PdfWriter 关联。接着,我们打开文档,向其中添加一个段落,并关闭文档。最后,将内存流转换为字节数组并通过 File 方法返回 PDF 文件。
2. 使用 PDF.js 预览 PDF 文件
我们可以使用 Mozilla 提供的开源 JavaScript 库 PDF.js 来在浏览器中预览 PDF 文件。可以通过以下步骤来实现:
Step 1. 引入库文件
将 PDF.js 相关的文件下载到本地,并将其引入到项目中。我们需要引入以下三个文件:
- pdf.js:PDF.js 主要文件;
- pdf.worker.js:PDF.js 的工作线程,用于异步解析 PDF 文件;
- viewer.html:用于预览 PDF 的 HTML 文件。
Step 2. 修改 HTML 文件
在 viewer.html 文件中,我们需要修改其中的 PDF_URL 和 PDF_TITLE 两个变量的值为生成 PDF 的地址和标题。代码示例如下:
<div id="outerContainer">
<div id="sidebarContainer">
<div id="toolbarSidebar">
<div class="splitToolbarButton toggled">
<button id="viewThumbnail" class="toolbarButton toggled"
title="Show Thumbnails" tabindex="2" data-l10n-id="thumbs">
<span data-l10n-id="thumbs_label">Thumbnails</span>
</button>
<button id="viewOutline" class="toolbarButton"
title="Show Document Outline (double-click to expand/collapse all items)"
tabindex="3" data-l10n-id="outline">
<span data-l10n-id="outline_label">Document Outline</span>
</button>
<button id="viewAttachments" class="toolbarButton"
title="Show Attachments" tabindex="4" data-l10n-id="attachments">
<span data-l10n-id="attachments_label">Attachments</span>
</button>
</div>
</div>
<div id="sidebarContent">
<div id="thumbnailView"></div>
<div id="outlineView" class="hidden"></div>
<div id="attachmentsView" class="hidden"></div>
</div>
</div> <!-- sidebarContainer -->
<div id="mainContainer">
<div class="findbar hidden doorHanger" id="findbar">
<label for="findInput" class="toolbarLabel" data-l10n-id="find_label">Find:</label>
<input id="findInput" class="toolbarField" tabindex="91">
<div class="splitToolbarButton">
<button class="toolbarButton findPrevious" title="" id="findPrevious"
tabindex="92" data-l10n-id="find_previous">
<span data-l10n-id="find_previous_label">Previous</span>
</button>
<div class="splitToolbarButtonSeparator"></div>
<button class="toolbarButton findNext" title="" id="findNext"
tabindex="93" data-l10n-id="find_next">
<span data-l10n-id="find_next_label">Next</span>
</button>
</div>
<input type="checkbox" id="findHighlightAll" class="toolbarField">
<label for="findHighlightAll" class="toolbarLabel" tabindex="94"
data-l10n-id="find_highlight">Highlight all</label>
<input type="checkbox" id="findMatchCase" class="toolbarField">
<label for="findMatchCase" class="toolbarLabel" tabindex="95"
data-l10n-id="find_match_case_label">Match case</label>
<span id="findMsg" class="toolbarLabel"></span>
</div> <!-- findbar -->
<div class="toolbar">
<div id="toolbarContainer">
<div id="toolbarViewer">
<div id="toolbarViewerLeft">
<button id="sidebarToggle" class="toolbarButton" title="Toggle Sidebar"
tabindex="11" data-l10n-id="toggle_sidebar">
<span data-l10n-id="toggle_sidebar_label">Toggle Sidebar</span>
</button>
<div class="toolbarButtonSpacer"></div>
<div class="splitToolbarButton">
<button class="toolbarButton pageUp" title="Previous Page"
id="previous" tabindex="13" data-l10n-id="previous">
<span data-l10n-id="previous_label">Previous</span>
</button>
<div class="splitToolbarButtonSeparator"></div>
<button class="toolbarButton pageDown" title="Next Page"
id="next" tabindex="14" data-l10n-id="next">
<span data-l10n-id="next_label">Next</span>
</button>
</div>
<label id="pageNumberLabel" class="toolbarLabel" for="pageNumber"
data-l10n-id="page_label">Page: </label>
<input type="number" id="pageNumber" class="toolbarField pageNumber"
value="1" size="4" min="1" tabindex="15">
<span id="numPages" class="toolbarLabel"></span>
</div>
<div id="toolbarViewerRight">
<div id="presentationMode" class="hidden">
<button id="presentationModeExit" class="toolbarButton presentationModeExit"
title="Leave Presentation Mode" tabindex="31"
data-l10n-id="presentation_mode_exit">
<span data-l10n-id="presentation_mode_exit_label">Exit Presentation Mode</span>
</button>
</div>
<button id="openFile" class="toolbarButton" title="Open File"
tabindex="21" data-l10n-id="open_file">
<span data-l10n-id="open_file_label">Open</span>
</button>
<button id="print" class="toolbarButton" title="Print"
tabindex="22" data-l10n-id="print">
<span data-l10n-id="print_label">Print</span>
</button>
<button id="download" class="toolbarButton" title="Download"
tabindex="23" data-l10n-id="download">
<span data-l10n-id="download_label">Download</span>
</button>
<a href="#" id="viewBookmark" class="toolbarButton" title="Current view (copy or open in new window)"
tabindex="24" data-l10n-id="bookmark">
<span data-l10n-id="bookmark_label">Current View</span>
</a>
<div class="verticalToolbarSeparator"></div>
<button id="secondaryToolbarToggle" class="toolbarButton" title="Tools"
tabindex="25" data-l10n-id="tools">
<span data-l10n-id="tools_label">Tools</span>
</button>
</div>
<div id="toolbarViewerMiddle">
<div class="splitToolbarButton">
<button id="zoomOut" class="toolbarButton zoomOut" title="Zoom Out"
tabindex="10" data-l10n-id="zoom_out">
<span data-l10n-id="zoom_out_label">Zoom Out</span>
</button>
<div class="splitToolbarButtonSeparator"></div>
<button id="zoomIn" class="toolbarButton zoomIn" title="Zoom In"
tabindex="11" data-l10n-id="zoom_in">
<span data-l10n-id="zoom_in_label">Zoom In</span>
</button>
</div>
<span id="scaleSelectContainer" class="dropdownToolbarButton">
<select id="scaleSelect" title="Zoom" tabindex="12" data-l10n-id="zoom">
<option id="pageAutoOption" title="" value="auto" selected="selected"
data-l10n-id="page_scale_auto">Automatic Zoom</option>
<option id="pageActualOption" title="" value="page-actual"
data-l10n-id="page_scale_actual">Actual Size</option>
<option id="pageFitOption" title="" value="page-fit"
data-l10n-id="page_scale_fit">Fit Page</option>
<option id="pageWidthOption" title="" value="page-width"
data-l10n-id="page_scale_width">Full Width</option>
<option id="customScaleOption" title="" value="custom"
disabled="disabled" hidden="true"></option>
<option value="0.5">50%</option>
<option value="0.75">75%</option>
<option value="1">100%</option>
<option value="1.25">125%</option>
<option value="1.5">150%</option>
<option value="2">200%</option>
</select>
</span>
</div>
</div>
<div id="loadingBar">
<div class="progress">
<div class="glimmer">
</div>
</div>
</div>
</div>
</div>
<div id="viewerContainer" tabindex="0">
<div id="viewer">
<div id="canvasContainer">
<div id="viewerCanvas"></div>
<div id="textLayerContainer" class="hidden"></div>
</div>
<div id="loadingBox">
<div id="loadingIcon"></div>
</div>
<div id="errorWrapper" hidden='true'>
<div id="errorMessageLeft">
<span id="errorMessage"></span>
<button id="errorShowMore" data-l10n-id="error_more_info">
More Information
</button>
<button id="errorShowLess" data-l10n-id="error_less_info" hidden='true'>
Less Information
</button>
</div>
<div id="errorMessageRight">
<button id="errorClose" data-l10n-id="error_close">
Close
</button>
</div>
<div class="clearBoth"></div>
<textarea id="errorMoreInfo" hidden='true' readonly="readonly"></textarea>
</div>
</div>
</div>
<div id="overlayContainer" class="hidden">
<div id="passwordOverlay" class="container hidden">
<div class="dialog">
<div class="row">
<p id="passwordText" data-l10n-id="password_label">Enter the password to open this PDF file:</p>
</div>
<div class="row">
<input type="password" id="password" class="toolbarField">
</div>
<div class="buttonRow">
<button id="passwordCancel" class="overlayButton"><span data-l10n-id="password_cancel">Cancel</span></button>
<button id="passwordSubmit" class="overlayButton"><span data-l10n-id="password_ok">OK</span></button>
</div>
</div>
</div>
<div id="documentPropertiesOverlay" class="container hidden">
<div class="dialog">
<div class="row">
<span data-l10n-id="document_properties_file_name">File name:</span> <p id="fileNameField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_file_size">File size:</span> <p id="fileSizeField">-</p>
</div>
<div class="separator"></div>
<div class="row">
<span data-l10n-id="document_properties_title">Title:</span> <p id="titleField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_author">Author:</span> <p id="authorField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_subject">Subject:</span> <p id="subjectField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_keywords">Keywords:</span> <p id="keywordsField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_creation_date">Creation Date:</span> <p id="creationDateField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_modification_date">Modification Date:</span> <p id="modificationDateField">-</p>
</div>
<div class="row">
<span data-l10n-id="document_properties_more_info">Additional Information:</span>
<p id="producerField">-</p>
<p id="versionField">-</p>
</div>
<div class="buttonRow">
<button id="documentPropertiesClose" class="overlayButton"><span data-l10n-id="document_properties_close">Close</span></button>
</div>
</div>
</div>
</div>
</div> <!-- mainContainer -->
</div> <!-- outerContainer -->
<script type="text/javascript">
PDFJS.getDocument("PDF_URL").promise.then(function(pdf) {
var total = pdf.numPages;
var currentPage = 1;
pdf.getPage(currentPage).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport({scale: scale});
var canvas = document.getElementById('viewerCanvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderTask = page.render({
canvasContext: context,
viewport: viewport
});
renderTask.promise.then(function() {
// do something
});
});
});
</script>
在上述代码中,我们将 HTML 文件中的 PDF_URL 变量的值设置为 ASP.NET MVC 生成的 PDF 文件的地址,如生成 PDF 的示例中的 GeneratePdf 方法返回的文件地址:"/Home/GeneratePdf"。
通过以上步骤,我们就可以在 ASP.NET MVC 项目中直接预览 PDF 文件了。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.NET MVC 项目直接预览PDF文件 - Python技术站