在 Web API 中生成 pdf (ItextSharp 5.5.13)



我需要在 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被下载时它是无用的,无法打开,我不明白为什么PDF无法打开,我认为这是Windows 10的安全性,所以一旦下载,我确实将其检查为安全文件,但它无论如何都无法打开。 我想我发送它的方式有问题,或者我在创建 PDF 文件时缺少一些东西

提前致谢

在关闭文档之前从内存流中检索字节:

pdfBytes = memStream.ToArray();
doc.Close(); //Close 
return pdfBytes;

但是在关闭文档之前,内存流中的 pdf 并不完整。因此,只需切换指令的顺序:

doc.Close(); //Close 
pdfBytes = memStream.ToArray();
return pdfBytes;

最新更新