【发布时间】:2019-01-07 21:45:32
【问题描述】:
在 ASP.NET Core 中工作并使用 iTextSharp,我正在构建 PDF 并将其保存到本地系统。我现在想在浏览器中打开该文件,但似乎无法完成这项工作,因为我在一次尝试中遇到了 FileStream 错误,而在另一次尝试中却什么也没有。
我的逻辑在下面的控制器中。我已经用// region description 替换了不必要的代码。重要的代码(我尝试过的东西)在TODO: Open the file 区域内。
控制器
[HttpPost]
public (JsonResult, IActionResult) CreatePDF([FromBody] ReportViewModel model)
{
try
{
// region Logic code
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
// Create the document
iTextSharp.text.Document document = new iTextSharp.text.Document();
// Place the document in the PDFWriter
iTextSharp.text.pdf.PdfWriter PDFWriter =
iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
// region Initialize Fonts
// Open the document
document.Open();
// region Add content to document
// Close the document
document.Close();
#region Create and Write the file
// Create the directory
string directory = $"{_settings.Value.ReportDirectory}\\";
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(directory));
// region Create the fileName
// Combine the directory and the fileName
directory = System.IO.Path.Combine(directory, fileName);
// Create the file
byte[] content = memoryStream.ToArray();
using (System.IO.FileStream fs = System.IO.File.Create(directory))
{
fs.Write(content, 0, (int)content.Length);
}
#endregion
#region TODO: Open the file
// TRY: File(Stream, type) => Newtonsoft.Json.JsonSerializationException:
// Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
// ---> System.InvalidOperationException: Timeouts are supported for this stream.
System.IO.FileStream fileStream = new System.IO.FileStream(directory, System.IO.FileMode.Open);
var returnPDF = File(fileStream, contentType: "application/pdf");
// TRY: File(path, type) => Newtonsoft.Json.JsonSerializationException:
// Error getting value from 'ReadTimeout' on 'System.IO.FileStream'.
// ---> System.InvalidOperationException: Timeouts are supported for this stream.
returnPDF = File(System.IO.File.OpenRead(directory), contentType: "application/pdf" );
// TRY: File(byte[], type) => Nothing happened
returnPDF = File(content, contentType: "apllication/pdf");
#endregion
return ( Json(new { isError = false }), returnPDF );
}
}
catch (System.Exception ex)
{
Serilog.Log.Error($"ReportController.CreatePDF() - {ex}");
return ( Json(new { isError = true, errorMessage = ex.Message }), null );
}
}
参考有用的 Stackoverflow 答案
【问题讨论】:
标签: c# pdf asp.net-core itext