【发布时间】:2017-12-23 08:13:42
【问题描述】:
我正在尝试在 C# 中使用 SelectPDF 发送 Byte Array 的转换 - HTML 到 PDF。我在下面给出的示例代码。我有一个 WebAPI,因为我正在这样做。我需要将 PDF 文档作为字节数组发送,并且需要在客户端 UI 中显示。以下代码未执行。
参考 SelectPDF 的文档https://selectpdf.com/docs/M_SelectPdf_PdfDocument_Save_3.htm
string html = "<html><body>hello world</body></html>";
PdfDocument doc = converter.ConvertHtmlString(html, "");
doc.Save(HttpContext.Current.Response, true, "C:\MyProject\Pdf\Sample.pdf");
如果我将 API 返回类型设为HttpResponseMessage,那么它可以正常工作,而不是返回 HttpContext.Current.Response(返回类型是 HttpResponse),它不工作。
工作代码
使用以下代码doc.Save(URL)将pdf保存到本地,然后需要读取文件(C# 4.0: Convert pdf to byte[] and vice versa)
请帮助我如何使用doc.Save(HttpContext.Current.Response, true, "C:\MyProject\Pdf\Sample.pdf");返回响应
注意:请提供解决方案,不要将文件保存在本地 (即,服务器本地)
工作 C# 代码:
public HttpResponseMessage GetSamplePDF() {
string html = "<html><body>hello world</body></html>";
PdfDocument doc = converter.ConvertHtmlString(html, "");
doc.Save("C:\MyProject\Pdf\Sample.pdf");
pdfData = System.IO.File.ReadAllBytes("C:\MyProject\Pdf\Sample.pdf");
var result = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new ByteArrayContent(reportdata)
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") {
FileName = "SamplePDF"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
此外,用户界面代码是Embed a Blob using PDFObject
【问题讨论】:
-
PDFDocument.Save()的签名是什么?它接受Stream吗?如果是这样,很可能Stream用于输入,而不是输出。但是我不熟悉那个,我用过iText。 -
@GlennFerrie - 请参考链接selectpdf.com/docs/M_SelectPdf_PdfDocument_Save_3.htm
-
If I make the API return type as HttpResponseMessage, then its working, instead of returning the HttpContext.Current.Response (Return type is HttpResponse), its not working.请告诉我们正在工作的确切代码,以及不工作的确切代码。 -
知道了。您的问题是最后一个参数应该是文件名,即 Sample.pdf。是下载时的文件名。 — 你不应该传递完整的路径。忘记我之前关于
Stream的评论 -
@GlennFerrie - 我更新了问题。请参考它包含工作代码的问题。
标签: c# pdf html-to-pdf