128

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

これが機能しない理由はありますか?

4

11 に答える 11

133

を返しますFileContentResult。コントローラー アクションの最後の行は次のようになります。

return File("Chap0101.pdf", "application/pdf");

MemoryStreamこの PDF を動的に生成する場合は、 を使用して、ファイルに保存するのではなく、メモリ内にドキュメントを作成する方がよい場合があります。コードは次のようになります。

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");
于 2009-10-02T16:13:20.863 に答える
70

私はそれをこのコードで動作させました。

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");    
}
于 2009-10-02T19:53:18.433 に答える
29

次を指定する必要があります。

Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")

ファイルをダウンロードするのではなく、ブラウザで直接開く

于 2014-04-02T18:04:38.340 に答える
18

FileResultアクション メソッドからを返しFile()、コントローラーで拡張メソッドを使用すると、必要なことを簡単に実行できます。ファイルのFile()バイナリ コンテンツ、ファイルへのパス、またはStream.

public FileResult DownloadFile()
{
    return File("path\\to\\pdf.pdf", "application/pdf");
}
于 2009-10-02T16:20:08.850 に答える
11

私は同様の問題に遭遇し、解決策に出くわしました。1 つはダウンロードのために戻る方法を示すスタックからのもので、もう1 つは 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");
}
于 2009-11-04T16:34:48.723 に答える
3

カスタム クラスを作成して、コンテンツ タイプを変更し、ファイルを応答に追加できます。

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

于 2009-10-02T16:05:10.407 に答える
3

この質問は古いことは知っていますが、似たようなものが見つからなかったので、これを共有すると思いました。

Razor を使用して通常どおりビュー/モデルを作成し、それらを Pdfs としてレンダリングしたかったのです。

このようにして、iTextSharp を使用してドキュメントをレイアウトする方法を理解するのではなく、標準の html 出力を使用して pdf プレゼンテーションを制御できました。

プロジェクトとソースコードは、ナゲットのインストール手順とともにここから入手できます。

https://github.com/andyhutch77/MvcRazorToPdf

Install-Package MvcRazorToPdf
于 2013-11-25T16:57:37.993 に答える
2

通常は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();
于 2009-11-04T16:41:47.517 に答える