8

PDF を生成して画面に表示したり、ユーザーがアクセスしやすい場所に保存したりできる必要がある ASP.Net MVC アプリを作成しています。ドキュメントの生成には PdfSharp を使用しています。完了したら、ユーザーがドキュメントを保存したり、リーダーで開いたりするにはどうすればよいでしょうか? PDFはサーバー側で生成されますが、クライアント側で表示したいので、特に混乱しています。


これまでに作成したレポートを作成するための MVC コントローラーは次のとおりです。

public class ReportController : ApiController
{
    private static readonly string filename = "report.pdf";

    [HttpGet]
    public void GenerateReport()
    {
        ReportPdfInput input = new ReportPdfInput()
        {
            //Empty for now
        };

        var manager = new ReportPdfManagerFactory().GetReportPdfManager();
        var documentRenderer = manager.GenerateReport(input);
        documentRenderer.PdfDocument.Save(filename); //Returns a PdfDocumentRenderer
        Process.Start(filename);
    }
}

これを実行すると、行が実行UnauthorizedAccessExceptionされたときに何が起こるかわかりません。documentRenderer.PdfDocument.Save(filename);Access to the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\report.pdf' is denied.Process.Start(filename);

のコードは次のmanager.GenerateReport(input)とおりです。

public class ReportPdfManager : IReportPdfManager
{
    public PdfDocumentRenderer GenerateReport(ReportPdfInput input)
    {
        var document = CreateDocument(input);
        var renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
        renderer.Document = document;
        renderer.RenderDocument();

        return renderer;
    }

    private Document CreateDocument(ReportPdfInput input)
    {
        //Put content into the document
    }
}
4

2 に答える 2

12

Yarx の提案と PDFsharp チームのチュートリアルを使用して、最終的に得られたコードは次のとおりです。

コントローラ:

[HttpGet]
public ActionResult GenerateReport(ReportPdfInput input)
{
    using (MemoryStream stream = new MemoryStream())
    {
        var manager = new ReportPdfManagerFactory().GetReportPdfManager();
        var document = manager.GenerateReport(input);
        document.Save(stream, false);
        return File(stream.ToArray(), "application/pdf");
    }
}

ReportPdfManager:

public PdfDocument GenerateReport(ReportPdfInput input)
{
    var document = CreateDocument(input);
    var renderer = new PdfDocumentRenderer(true,
        PdfSharp.Pdf.PdfFontEmbedding.Always);
    renderer.Document = document;
    renderer.RenderDocument();

    return renderer.PdfDocument;
}

private Document CreateDocument(ReportPdfInput input)
{
    //Creates a Document and puts content into it
}
于 2013-02-28T20:34:11.477 に答える
8

私はPDFシャープに慣れていませんが、MVCの場合、ほとんどが組み込み機能を介して行われます。バイト配列として表される PDF ドキュメントを取得する必要があります。次に、MVC の File メソッドを使用してブラウザに返し、ダウンロードを処理させます。それを行うためのクラスにメソッドはありますか?

public class PdfDocumentController : Controller
{
    public ActionResult GenerateReport(ReportPdfInput input)
    {
        //Get document as byte[]
        byte[] documentData;

        return File(documentData, "application/pdf");
    }

}
于 2013-02-27T22:02:35.990 に答える