gpt4 book ai didi

javascript - 从 iTextSharp 生成 Base64

转载 作者:行者123 更新时间:2023-11-30 15:21:23 25 4
gpt4 key购买 nike

我的项目中有如下方法。

        [Route("GerarPdf")]
[HttpGet()]
public object GerarPdf()
{

var doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
var mem = new MemoryStream();

PdfWriter wri = PdfWriter.GetInstance(doc, mem);

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

var pdf = mem.ToArray();

return Convert.ToBase64String(pdf);
}

此代码的目的是生成可通过以下 JavaScript 代码下载的 PDF 文件

     var dataURI = "data:application/pdf;base64," +result;
window.open(dataURI,'_blank');

但是新打开的页面在加载 PDF 时总是返回错误。该方法返回给result变量的base64编码为:

JVBERi0xLjQKJeLjz9MK

谁能帮我解决这个问题?

最佳答案

问题是在转换为 bytearray 时文档没有关闭。在我添加 doc.Close(); 之后PDF 已成功生成。

        [Route("GerarPdf")]
[HttpGet()]
public object GerarPdf()
{

var doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
var mem = new MemoryStream();

PdfWriter wri = PdfWriter.GetInstance(doc, mem);

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

doc.Close();

var pdf = mem.ToArray();

return Convert.ToBase64String(pdf);
}

关于javascript - 从 iTextSharp 生成 Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com