ボタンをクリックすると、サーバー上にPDFを作成し、ブラウザの新しいタブで開きます。 PDFはうまく生成されますが、ブラウザをダウンロードせずに開くことはできません。 IEではファイルを認識せず、Chromeではダウンロードを促します。どんな助けもありがとうございます。私のコードは以下の通りです:PDFサーバー側を作成し、新しいブラウザのウィンドウまたはタブで開く
C#のコントローラー、それはまだ新しいタブで開くのではなく、ファイルをダウンロードするよう
public string CreateCustomReport()
{
var doc = new Document();
MemoryStream m = new MemoryStream();
try
{
string query = "";
PdfWriter.GetInstance(doc, m).CloseStream = false;
SqlConnection conn = new SqlConnection(conn);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader sqdr = cmd.ExecuteReader();
doc.Open();
PdfPTable table = new PdfPTable(4);
PdfPCell cell = new PdfPCell(new Phrase(customTitle));
cell.Colspan = 4;
table.AddCell(cell);
table.AddCell(groupBy);
table.AddCell(col1);
table.AddCell(col2);
table.AddCell("Event");
while (sqdr.Read())
{
table.AddCell(Convert.ToString(sqdr["GroupBy"].ToString()));
table.AddCell(Convert.ToString(sqdr["Col1"].ToString()));
table.AddCell(Convert.ToString(sqdr["Col2"].ToString()));
table.AddCell(Convert.ToString(sqdr["Events"].ToString()));
}
doc.Add(table);
doc.Close();
}
catch (Exception)
{
}
return System.Convert.ToBase64String(m.ToArray());
}
jQueryの
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
url: '@Url.Action("CreateCustomReport")',
error: function(error) {
debugger;
alert("Search failed.");
},
success: function(data) {
var openpdf = $('<a id="openpdf" download="Report.pdf" href="data:application/pdf;base64,' + data + '" target="new">');
$('body').append(openpdf);
document.getElementById("openpdf").click();
$("#openpdf").remove();
}
});
これははるかにクリーンですが、PDFはユーザーの入力に基づいて生成され、ユーザーがボタンをクリックして送信すると返信する必要があるため、自分のやり方と同じようにしています。私は、それらが関連しているとは思わなかったので、引数をCreateCustomReportメソッドに除外しました。 –