Как возвратить PDF браузеру в MVC?

Я не думаю так, по крайней мере, не просто в Java, но почему необходимо сделать это? В Java предпочтительно использовать свойства через System.getProperties(), который можно изменить.

, Если Вы действительно должны, я уверен, что Вы могли бы перенести функцию C setenv в вызов JNI - на самом деле, я не буду удивлен, сделал ли кто-то так уже. Я не знаю детали кода, все же.

117
задан hutchonoid 26 May 2016 в 08:08
поделиться

6 ответов

У меня он работает с этим кодом.

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");    
}
60
ответ дан 24 November 2019 в 02:06
поделиться

Вернуть 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");
125
ответ дан 24 November 2019 в 02:06
поделиться

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");
}
16
ответ дан 24 November 2019 в 02:06
поделиться

You can create a custom class to modify the content type and add the file to the response.

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

3
ответ дан 24 November 2019 в 02:06
поделиться

Обычно вы выполняете Response.Flush, а затем Response.Close, но по некоторым причинам библиотеке iTextSharp это не нравится. Данные не проходят, и Adobe считает, что PDF-файл поврежден. Оставьте функцию Response.Close и посмотрите, будут ли ваши результаты лучше:

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();
2
ответ дан 24 November 2019 в 02:06
поделиться

У меня были похожие проблемы, и я нашел решение. Я использовал два сообщения: одно из стека , которое показывает метод возврата для загрузки, а другое , одно , которое показывает рабочее решение для 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");
}
11
ответ дан 24 November 2019 в 02:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: