如何在.NET Core中使用iText7库生成PDF。

huangapple go评论71阅读模式
英文:

How to generate PDF in NET core using iText7 library

问题

I'm using NET Core 6 and I'm playing with the PDF documents or to be more precise how to create PDF documents using iText7 nuget library but it seems that I'm doing something wrong here since I'm getting this response in swagger:

如何在.NET Core中使用iText7库生成PDF。

And simple sample of the code for generating PDF is this:

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();
}

And this should be API response:

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");
}

Please, what I'm doing wrong and thank you in advance.

英文:

I'm using NET Core 6 and I'm playing with the PDF documents or to be more precise how to create PDF documents using iText7 nuget library but it seems that I'm doing something wrong here since I'm getting this response in swagger:

如何在.NET Core中使用iText7库生成PDF。

And simple sample of the code for generating PDF is this:

 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(&quot;dwawwa&quot;);

            var headerCell = new Cell().Add(new Paragraph(&quot;Invoice&quot;));
            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(&quot;Invoice Number&quot;);
            detailsTable.AddCell(&quot;12&quot;);

            detailsTable.AddCell(&quot;Date&quot;);
            detailsTable.AddCell(DateTime.Now.ToString(&quot;dd/MM/yyyy&quot;));

            // 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(&quot;Thank you for your business!&quot;));
            footerCell.SetTextAlignment(TextAlignment.CENTER);
            footerTable.AddCell(footerCell);

            document.Add(footerTable);

            document.Close();

            return memoryStream.ToArray();
        }

And this should be API response:

public async Task&lt;IActionResult&gt; GetInvoicePDF()
{
    var response = CreateInvoiceDocument();

    if (response == null)
        return BadRequest(&quot;Failed to generate the PDF.&quot;);

    var stream = new MemoryStream(response);
    return new FileStreamResult(stream, &quot;application/pdf&quot;);
}

Please, what I'm doing wrong nad thank you in advance.

答案1

得分: 1

尝试使用 FileContentResult,它继承自 IActionResult,但有助于Swagger识别它为SwaggerUI中的文件。

public async Task<FileContentResult> GetInvoicePDF()
{
    var response = CreateInvoiceDocument();

    if (response == null)
        return BadRequest("生成PDF失败。");

    var stream = new MemoryStream(response);
    FileContentResult file = new FileContentResult(stream.ToArray(), "application/pdf")
    {
        FileDownloadName = Path.GetFileName("yourfilename.pdf")
    };

    return file;
}
英文:

Try to use FileContentResult which inherits from IActionResult but helps Swagger to recognize it as a file in SwaggerUI.

public async Task&lt;FileContentResult&gt; GetInvoicePDF()
{
 var response = CreateInvoiceDocument();

 if (response == null)
    return BadRequest(&quot;Failed to generate the PDF.&quot;);

 var stream = new MemoryStream(response);
 FileContentResult file = new FileContentResult(stream.ToArray(), &quot;application/pdf&quot;)
 {
   FileDownloadName = Path.GetFileName(&quot;yourfilename.pdf&quot;)
 };

 return file;
}

答案2

得分: 0

After adding MediaTypeNames.Application.Pdf into FileContentResult everything work as expected. Thank you all and hope that code below will help you in the future

在将MediaTypeNames.Application.Pdf添加到FileContentResult后,一切都按预期运行。谢谢大家,希望下面的代码对您有帮助。

英文:

Ok, after a while I finally figure it out.After adding MediaTypeNames.Application.Pdf into FileContentResult everything work as expected.
Thank you all and hope that code below will help you in the future

public async Task&lt;FileContentResult&gt; GetInvoicePDF()
{
    var response = CreateInvoiceDocument();

    if (response == null)
        return BadRequest(&quot;Failed to generate the PDF.&quot;);

    var stream = new MemoryStream(response);
    var result = new FileContentResult(response, MediaTypeNames.Application.Pdf)
    {
        FileDownloadName = &quot;test.pdf&quot;
    };

    return result;
}

huangapple
  • 本文由 发表于 2023年6月29日 05:47:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定