MVC에서 PDF를 브라우저로 반환하는 방법은 무엇입니까?
iTextSharp에 대한 데모 코드가 있습니다
Document document = new Document();
try
{
PdfWriter.GetInstance(document, new FileStream("Chap0101.pdf", FileMode.Create));
document.Open();
document.Add(new Paragraph("Hello World"));
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
document.Close();
컨트롤러가 PDF 문서를 브라우저로 반환하도록하려면 어떻게해야합니까?
편집하다:
이 코드를 실행하면 Acrobat이 열리지 만 "파일이 손상되어 복구 할 수 없습니다"라는 오류 메시지가 나타납니다.
public FileStreamResult pdf()
{
MemoryStream m = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, m);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Add(new Paragraph(DateTime.Now.ToString()));
m.Position = 0;
return File(m, "application/pdf");
}
왜 이것이 효과가 없는지 아십니까?
a를 반환합니다 FileContentResult
. 컨트롤러 작업의 마지막 줄은 다음과 같습니다.
return File("Chap0101.pdf", "application/pdf");
이 PDF를 동적으로 생성하는 경우을 사용하고 MemoryStream
파일로 저장하는 대신 메모리에 문서를 작성하는 것이 좋습니다. 코드는 다음과 같습니다.
Document document = new Document();
MemoryStream stream = new MemoryStream();
try
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
pdfWriter.CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
document.Close();
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
return File(stream, "application/pdf", "DownloadName.pdf");
이 코드로 작업했습니다.
using iTextSharp.text;
using iTextSharp.text.pdf;
public FileStreamResult pdf()
{
MemoryStream workStream = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, workStream).CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
document.Add(new Paragraph(DateTime.Now.ToString()));
document.Close();
byte[] byteInfo = workStream.ToArray();
workStream.Write(byteInfo, 0, byteInfo.Length);
workStream.Position = 0;
return new FileStreamResult(workStream, "application/pdf");
}
다음을 지정해야합니다.
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")
파일을 다운로드 하지 않고 브라우저에서 직접 열 려면
If you return a FileResult
from your action method, and use the File()
extension method on the controller, doing what you want is pretty easy. There are overrides on the File()
method that will take the binary contents of the file, the path to the file, or a Stream
.
public FileResult DownloadFile()
{
return File("path\\to\\pdf.pdf", "application/pdf");
}
I've run into similar problems and I've stumbled accross a solution. I used two posts, one from stack that shows the method to return for download and another one that shows a working solution for ItextSharp and MVC.
public FileStreamResult About()
{
// Set up the document and the MS to write it to and create the PDF writer instance
MemoryStream ms = new MemoryStream();
Document document = new Document(PageSize.A4.Rotate());
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// Open the PDF document
document.Open();
// Set up fonts used in the document
Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 19, Font.BOLD);
Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9);
// Create the heading paragraph with the headig font
Paragraph paragraph;
paragraph = new Paragraph("Hello world!", font_heading_1);
// Add a horizontal line below the headig text and add it to the paragraph
iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator();
seperator.Offset = -6f;
paragraph.Add(seperator);
// Add paragraph to document
document.Add(paragraph);
// Close the PDF document
document.Close();
// Hat tip to David for his code on stackoverflow for this bit
// https://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf
byte[] file = ms.ToArray();
MemoryStream output = new MemoryStream();
output.Write(file, 0, file.Length);
output.Position = 0;
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");
// Return the output stream
return File(output, "application/pdf"); //new FileStreamResult(output, "application/pdf");
}
You can create a custom class to modify the content type and add the file to the response.
I know this question is old but I thought I would share this as I could not find anything similar.
I wanted to create my views/models as normal using Razor and have them rendered as Pdfs.
This way I had control over the pdf presentation using standard html output rather than figuring out how to layout the document using iTextSharp.
The project and source code is available here with nuget installation instructions:
https://github.com/andyhutch77/MvcRazorToPdf
Install-Package MvcRazorToPdf
You would normally do a Response.Flush followed by a Response.Close, but for some reason the iTextSharp library doesn't seem to like this. The data doesn't make it through and Adobe thinks the PDF is corrupt. Leave out the Response.Close function and see if your results are better:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-disposition", "attachment; filename=file.pdf"); // open in a new window
Response.OutputStream.Write(outStream.GetBuffer(), 0, outStream.GetBuffer().Length);
Response.Flush();
// For some reason, if we close the Response stream, the PDF doesn't make it through
//Response.Close();
HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");
if the filename is generating dynamically then how to define filename here, it is generating through guid here.
if you return var-binary data from DB to display PDF on popup or browser means follow this code:-
View page:
@using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
{
<a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
}
Scan controller:
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB(4);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=@Id and Enabled = 1";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["Scan_Pdf_File"];
}
}
con.Close();
}
}
return bytes;
#endregion
}
FileStreamResult
certainly works. But if you look at the Microsoft Docs, it inherits from ActionResult -> FileResult
, which has another derived class FileContentResult
. It "sends the contents of a binary file to the response". So if you already have the byte[]
, you should just use FileContentResult
instead.
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromWhatever();
return new FileContentResult(byteArray, "application/pdf");
}
참고URL : https://stackoverflow.com/questions/1510451/how-to-return-pdf-to-browser-in-mvc
'Programing' 카테고리의 다른 글
HTML / css로 Chrome / Safari 맞춤법 검사 기능 끄기 (0) | 2020.07.21 |
---|---|
int를 사용하여 python dataframe pandas drop column (0) | 2020.07.21 |
다른 UIView에서 UIView와의 상호 작용 허용 (0) | 2020.07.21 |
start-stop-daemon으로 시작한 프로세스의 stdout을 어떻게 기록 할 수 있습니까? (0) | 2020.07.21 |
반응, ES6-getInitialState가 일반 JavaScript 클래스에 정의되었습니다. (0) | 2020.07.21 |