【发布时间】:2018-09-25 16:44:29
【问题描述】:
我需要在 web api 的内存中创建一个 PDF 文件并发送它我确实创建了 PDF 并且 web api 发送它,但我无法打开它一次收到。
我确实将 PDF 创建为字节数组:
private byte[] createPDF()
{
MemoryStream memStream = new MemoryStream();
byte[] pdfBytes;
Document doc = new Document(iTextSharp.text.PageSize.LETTER);
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
doc.AddTitle("test");
doc.AddCreator("I am");
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
pdfBytes = memStream.ToArray();
doc.Close(); //Close
return pdfBytes;
}
这个方法被发送PDF的web api中的方法调用,就是这个:
[HttpGet]
public HttpResponseMessage GetFiniquitopdf()
{
try
{
byte[] buffer = createPDF();
response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = buffer.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "myFirstPDF.pdf"
};
}
catch (Exception e)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
return response;
}
问题是下载的时候PDF没用,打不开,不明白为什么打不开,我以为是安全问题windows10,所以一旦下载,我会检查它作为一个安全文件,但它无论如何都不会打开 我想我发送它的方式有问题,或者我在创建 PDF 文件时缺少一些东西
提前致谢
【问题讨论】:
标签: asp.net-web-api itext