programing

MVC에서 PDF를 브라우저로 되돌리는 방법은 무엇입니까?

closeapi 2023. 5. 16. 22:41
반응형

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");
    }

이것이 왜 효과가 없는지에 대한 아이디어가 있습니까?

반환 aFileContentResult컨트롤러 작업의 마지막 행은 다음과 같습니다.

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")

파일을 다운로드하지 않고 브라우저에서 직접 여는 경우

반환하는 경우FileResult당신의 행동 방식에서, 그리고 사용합니다.File()컨트롤러의 확장 방법, 원하는 것을 하는 것은 매우 쉽습니다.에 오버라이드가 있습니다.File()파일의 이진 내용, 파일에 대한 경로를 취하는 방법 또는Stream.

public FileResult DownloadFile()
{
    return File("path\\to\\pdf.pdf", "application/pdf");
}

저는 비슷한 문제에 부딪혔고 우연히 해결책을 발견했습니다.저는 두 개의 게시물을 사용했는데, 하나는 다운로드를 위해 반환하는 방법을 보여주는 스택의 게시물이고 다른 하나는 ItextSharp와 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");
}

FileStreamResult확실히 효과가 있습니다.하지만 Microsoft Docs를 보면 다음과 같이 상속됩니다.ActionResult -> FileResult다른 파생 클래스를 갖는.이진 파일의 내용을 응답으로 보냅니다.그래서 만약 당신이 이미 가지고 있다면.byte[]당신은 그냥 사용해야 합니다.FileContentResult대신.

public ActionResult DisplayPDF()
{
    byte[] byteArray = GetPdfFromWhatever();

    return new FileContentResult(byteArray, "application/pdf");
}

사용자 정의 클래스를 만들어 내용 유형을 수정하고 응답에 파일을 추가할 수 있습니다.

http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

저는 이 질문이 오래된 질문이라는 것을 알지만, 비슷한 것을 찾을 수 없었기 때문에 저는 이것을 공유하려고 생각했습니다.

저는 Razor를 사용하여 제 뷰/모델을 정상적으로 생성하여 Pdfs로 렌더링하고 싶었습니다.

이렇게 하면 iTextSharp를 사용하여 문서를 레이아웃하는 방법을 알아내는 대신 표준 html 출력을 사용하여 pdf 프레젠테이션을 제어할 수 있었습니다.

프로젝트 및 소스 코드는 너트 설치 지침과 함께 제공됩니다.

https://github.com/andyhutch77/MvcRazorToPdf

Install-Package MvcRazorToPdf

일반적으로 반응을 수행합니다.플러시 후에 응답이 나타납니다.닫히지만 어떤 이유에서인지 iTextSharp 라이브러리는 이것을 좋아하지 않는 것 같습니다.데이터가 전송되지 않고 Adobe는 PDF가 손상되었다고 생각합니다.응답을 생략합니다.기능을 닫고 결과가 더 나은지 확인합니다.

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");

파일 이름이 동적으로 생성되면 여기서 파일 이름을 정의하는 방법은 GUID를 통해 생성됩니다.

PDF를 팝업 또는 브라우저에 표시하기 위해 DB에서 var-binary 데이터를 반환하는 경우 다음 코드를 따릅니다.

페이지 보기:

@using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
    {
        <a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
    }

스캔 컨트롤러:

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
        }

언급URL : https://stackoverflow.com/questions/1510451/how-to-return-pdf-to-browser-in-mvc

반응형