使用itextsharp 4.2.0,我已经使用以下函数在内存中生成虚拟PDF并将其发送回客户端:
internal override byte[] GeneratePDFDocument(pdfContent content)
{
Document document = new Document(PageSize.A4, 30f, 30f, 30f, 30f);
MemoryStream output = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, output);
document.Open();
document.Add(new Paragraph("Hello World"));
byte[] response = output.ToArray();
document.Close();
return response;
}
从静态函数调用:
public static byte[] Print(string jsonData)
{
PDFGeneratorBase generator;
generator = new ITextSharpGenerator();
return generator.GeneratePDFDocument(view.GetViewData());
}
从WebAPI控制器调用:
public HttpResponseMessage PrintPDF(HttpRequestMessage req)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
byte[] pdfData = PrintReport.Print(printJobString);
result.Content = new ByteArrayContent(pdfData);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "PrintPDF.pdf";
return result;
}
如果我在福昕阅读器7.2中打开生成的PDF,则错误消息为"格式错误:不是PDF或损坏"。
我在这里做错了什么?
答案 0 :(得分:2)
您需要在抓取字节数组之前关闭文档。关闭文档会刷新&#34的内部缓冲区;完成"该文件。交换这个:
$('#example').DataTable( {
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 2 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column( 2 ).footer() ).html('$' + total);
}
} );
有了这个:
byte[] response = output.ToArray();
document.Close();