所以我整天都在搜索这些内容,但我只是不知道如何使它工作。基本上,我想在ASP.Net WebApi中使用iText 7创建PDF服务器端。非常简单直接的Pdf创建:
[HttpGet]
public HttpResponseMessage CreateLieferschein()
{
MemoryStream stream = new MemoryStream();
PdfWriter writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello World!"));
}
从这里开始,我不知道如何从控制器返回文件。我真的很感激,因为我迷路了。
答案 0 :(得分:2)
我还没有尝试过,只是徒手完成,所以请耐心等待,但是我想您可以了解这里发生的事情。
public HttpResponseMessage CreateLieferschein() {
// Create the itext pdf
MemoryStream stream = new MemoryStream();
PdfWriter writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello World!"));
document.Close(); // don't forget to close or the doc will be corrupt! ;)
// Load the mem stream into a StreamContent
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
// Prep the response with headers, filenames, etc.
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "WebApi2GeneratedFile.pdf"
};
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
// Cross your fingers...
return responseMessageResult;
}
答案 1 :(得分:0)
尝试:
[HttpGet]
public HttpResponseMessage CreateLieferschein()
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
byte[] buffer;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest);
using(MemoryStream stream = new MemoryStream())
{
using(PdfWriter wri = PdfWriter.GetInstance(doc, mem))
{
PdfWriter writer = new PdfWriter(stream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
document.Add(new Paragraph("Hello World!"));
}
buffer = stream.ToArray();
var contentLength = buffer.Length;
var statuscode = HttpStatusCode.OK;
response = Request.CreateResponse(statuscode);
response.Content = new StreamContent(new MemoryStream(buffer));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentLength = contentLength;
ContentDispositionHeaderValue contentDisposition = null;
if (ContentDispositionHeaderValue.TryParse("inline; filename=" + document.Name + ".pdf", out contentDisposition)) {
response.Content.Headers.ContentDisposition = contentDisposition;
}
} else {
var statuscode = HttpStatusCode.NotFound;
var message = String.Format("Unable to find file. file \"{0}\" may not exist.", docid);
var responseData = responseDataFactory.CreateWithOnlyMetadata(statuscode, message);
response = Request.CreateResponse((HttpStatusCode)responseData.meta.code, responseData);
}
return response;
}