我正在使用 NET Core 6,我正在处理 PDF 文档,或者更准确地说,如何使用 iText7 nuget 库创建 PDF 文档,但似乎我在这里做错了,因为我在昂首阔步:
生成 PDF 的简单代码示例如下:
private static byte[] CreateInvoiceDocument()
{
using var memoryStream = new MemoryStream();
var writer = new PdfWriter(memoryStream);
var pdf = new PdfDocument(writer);
pdf.SetDefaultPageSize(PageSize.A4);
var document = new Document(pdf);
// Header table
var headerTable = new Table(1);
headerTable.SetWidth(UnitValue.CreatePercentValue(100));
var test = new Paragraph("dwawwa");
var headerCell = new Cell().Add(new Paragraph("Invoice"));
headerCell.SetTextAlignment(TextAlignment.CENTER);
headerTable.AddCell(headerCell);
document.Add(headerTable);
// Invoice details table
var detailsTable = new Table(2);
detailsTable.SetWidth(UnitValue.CreatePercentValue(100));
detailsTable.SetMarginTop(20);
detailsTable.AddCell("Invoice Number");
detailsTable.AddCell("12");
detailsTable.AddCell("Date");
detailsTable.AddCell(DateTime.Now.ToString("dd/MM/yyyy"));
// Add more details as needed
document.Add(detailsTable);
// Footer
var footerTable = new Table(1);
footerTable.SetWidth(UnitValue.CreatePercentValue(100));
footerTable.SetMarginTop(20);
var footerCell = new Cell().Add(new Paragraph("Thank you for your business!"));
footerCell.SetTextAlignment(TextAlignment.CENTER);
footerTable.AddCell(footerCell);
document.Add(footerTable);
document.Close();
return memoryStream.ToArray();
}
这应该是 API 响应:
public async Task<IActionResult> GetInvoicePDF()
{
var response = CreateInvoiceDocument();
if (response == null)
return BadRequest("Failed to generate the PDF.");
var stream = new MemoryStream(response);
return new FileStreamResult(stream, "application/pdf");
}
请告诉我我做错了什么,提前谢谢你。
尝试使用FileContentResult,它继承自IActionResult,但可以帮助Swagger将其识别为SwaggerUI中的文件。
public async Task<FileContentResult> GetInvoicePDF()
{
var response = CreateInvoiceDocument();
if (response == null)
return BadRequest("Failed to generate the PDF.");
var stream = new MemoryStream(response);
FileContentResult file = new FileContentResult(stream.ToArray(), "application/pdf")
{
FileDownloadName = Path.GetFileName("yourfilename.pdf")
};
return file;
}
好吧,过了一会儿我终于弄清楚了。将 MediaTypeNames.Application.Pdf 添加到 FileContentResult 后,一切都按预期工作。 谢谢大家,希望下面的代码对您将来有所帮助
public async Task<FileContentResult> GetInvoicePDF()
{
var response = CreateInvoiceDocument();
if (response == null)
return BadRequest("Failed to generate the PDF.");
var stream = new MemoryStream(response);
var result = new FileContentResult(response, MediaTypeNames.Application.Pdf)
{
FileDownloadName = "test.pdf"
};
return result;
}
您可能想尝试使用 ZetPDF.com 用 C# 生成 PDF 文件。它对我来说效果很好。